Подход 1 : создание представления нижнего колонтитула с UIView
в коде
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let footerRect = CGRect(x: 0, y: 0, width: tableView.bounds.width, height: 40.0)
let footerView = UIView(frame: footerRect)
footerView.backgroundColor = UIColor.green
let label = UILabel(frame: CGRect(x: 0.0, y: 4.0, width: 200.0, height: 20.0))
label.text = "Hello"
footerView.addSubview(label)
return footerView
}
Подход 2 : создание представления нижнего колонтитула с подключенным к IBOutlet UIView
(.xib) объектом
a) Создайте файл View, выбрав File> New> File. Выберите View под пользовательским интерфейсом. Назовите файл. Например, имя FooterView.xib.
b) Создайте файл подкласса UIView
, выбрав «Файл»> «Создать»> «Файл». Выберите Какао Touch Class под источником. Назовите файл после выбора подкласса UIView. Например, имя FooterView.swift.
в) Выберите файл View
. И выберите File's Owner
в средней панели. Затем установите имя подкласса UIView
(FooterView) в качестве класса. Откройте файл View
и файл UIView subclass
. Установите соединение IBOutlet последнего с Content View
первого.
import UIKit
class FooterView: UIView {
@IBOutlet var contentView: UIView!
@IBOutlet weak var myLabel: UILabel!
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
Bundle.main.loadNibNamed("FooterView", owner: self, options: nil)
addSubview(contentView)
contentView.frame = self.bounds
}
override func awakeFromNib() {
super.awakeFromNib()
myLabel.text = "My footer"
}
}
d) Добавить объект UIView
в контроллер представления. (См. Рисунок ниже.) Установите имя класса (FooterView).
e) Подключите объект вида нижнего колонтитула к контроллеру вида.
f) Подготовка к табличному представлению viewForFooterInSection
метод делегата.
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// MARK: - Variables
let list = ["George", "Nancy", "Jim"]
// MARK: - IBOutlet
@IBOutlet var footerView: FooterView!
@IBOutlet weak var tableView: UITableView!
// MARK: - IBAction
// MARK: - Life cycle
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - TableView
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return list.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = list[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let footerRect = CGRect(x: 0, y: 0, width: tableView.bounds.width, height: 40.0)
footerView.frame = footerRect
return footerView
}
}