Я пытаюсь создать собственный фон для моего раздела tableview. Мне нужен следующий вид:
Как мне настроить фон/слой раздела tableview, а не только отдельные ячейки?
Редактировать: просто для уточнения — я говорю о белом фоне в разделе «Последние транзакции». Таким образом, верхняя часть секции закруглена (как и нижняя), но все ряды прямоугольные.
О каком фоне раздела на изображении вы говорите?
Просто для уточнения — я говорю о белом фоне в разделе «Последние транзакции». Таким образом, верхняя часть секции закруглена (как и нижняя), но все ряды прямоугольные.
Взгляните на func headerView(forSection section: Int) -> UITableViewHeaderFooterView?
headerView(forSection:) — UITableView | Apple Разработчик
Используйте метод UITableViewDelegate
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
<#code#>
}
Это поможет вам настроить вид заголовка каждого раздела программно.
Чтобы создать заголовок раздела в tableView
, используйте методы UITableViewDelegate's
tableView(_:viewForHeaderInSection:)
и tableView(_:heightForHeaderInSection:)
.
func getHeaderText(for section: Int) -> String? {
switch section {
case 0:
return "Latest Transactions"
default:
return "Other Transactions"
}
//Add other cases for different sections
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView(frame: CGRect(origin: .zero, size: CGSize(width: UIScreen.main.bounds.width, height: 70.0)))
headerView.backgroundColor = .clear
let label = UILabel(frame: CGRect(x: 20, y: 0, width: headerView.bounds.width - 40, height: headerView.bounds.height))
label.text = self.getHeaderText(for: section)
label.font = UIFont.systemFont(ofSize: 16.0, weight: .semibold)
headerView.addSubview(label)
return headerView
//Customize the headerView as per your requirement
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 70.0
}
В приведенном выше коде вы можете настроить header label
в getHeaderText(for:)
для каждого section
.
Кроме того, я создал headerView
программно. Вы также можете использовать .xib
для создания пользовательского headerView
. Это полностью ваш выбор.
Вы можете настроить headerView
в соответствии с вашими требованиями либо программно, либо в интерфейсе.
Создайте подкласс UITableViewCell
и добавьте UIView
белого цвета. Добавьте левое и правое заполнение для представления в ячейку. Добавьте UILabel
и другие элементы UI
в этот недавно добавленный вид вместо добавления cell
или его contentView
. Установите cell
цвет фона как UIColor.groupTableViewBackground
class CustomCell: UITableViewCell {
let bgView = UIView()
let label = UILabel()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit() {
backgroundColor = .groupTableViewBackground
bgView.backgroundColor = .white
bgView.translatesAutoresizingMaskIntoConstraints = false
addSubview(bgView)
label.translatesAutoresizingMaskIntoConstraints = false
bgView.addSubview(label)
bgView.topAnchor.constraint(equalTo: topAnchor).isActive = true
bgView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
bgView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10).isActive = true
bgView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10).isActive = true
label.heightAnchor.constraint(equalToConstant: 30).isActive = true
label.topAnchor.constraint(equalTo: bgView.topAnchor, constant: 5).isActive = true
label.bottomAnchor.constraint(equalTo: bgView.bottomAnchor, constant: -5).isActive = true
label.leadingAnchor.constraint(equalTo: bgView.leadingAnchor, constant: 5).isActive = true
label.trailingAnchor.constraint(equalTo: bgView.trailingAnchor, constant: -5).isActive = true
}
}
Используйте этот класс ячеек в своем tableView
. И установите цвет фона контроллера представления и цвет фона tableView
как UIColor.groupTableViewBackground
В cellForRowAt
проверьте, является ли ячейка первой или последней ячейкой раздела. Если это первая ячейка раздела, примените угловой радиус к верхнему левому и верхнему правому углам. Если ячейка является последней ячейкой раздела, примените угловой радиус к нижнему левому и нижнему правому углам. Если ячейка находится посередине, удалите угловой радиус.
class TableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
tableView.backgroundColor = .groupTableViewBackground
tableView.register(CustomCell.self, forCellReuseIdentifier: "CustomCell")
tableView.separatorInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 10)
tableView.tableFooterView = UIView()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Section \(section) Title"
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell") as? CustomCell
?? CustomCell(style: .default, reuseIdentifier: "CustomCell")
if indexPath.row == 0 {//first cell of this section
cell.bgView.layer.cornerRadius = 15.0
cell.bgView.layer.masksToBounds = true
cell.bgView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
} else if indexPath.row == tableView.numberOfRows(inSection: indexPath.section)-1 {//last cell of this section
cell.bgView.layer.cornerRadius = 15.0
cell.bgView.layer.masksToBounds = true
cell.bgView.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]
} else {
cell.bgView.layer.cornerRadius = 0
}
cell.label.text = "Row \(indexPath.row)"
return cell
}
}
Вы говорите об этом закругленном прямоугольном фоне белого цвета? Вы можете просто установить фон для отдельных ячеек. Первая и последняя ячейки раздела должны иметь закругленное изображение. другие ячейки должны иметь прямоугольное изображение.