UITableView 底部的静态单元格

Static cell at the bottom of a UITableView

我有一个充满联系人的 table 视图。在 table 视图的最底部(在最后一次联系之后)我想要一个静态的 table 视图单元格,它总是带有自定义内容。

我怎样才能做到这一点?

假设您用来填充 UITableView 的数组称为 'contactsArray'。

您需要在以下委托方法中添加一行,例如:

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return contactsArray+1

}

然后你需要处理这个逻辑,例如:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

if indexPath.row >= contactsArray.count{
        print("Last Row")
    }
} 

示例如下:

override func viewDidLoad() {
    super.viewDidLoad()

    let button = UIButton.init()
    button.frame = CGRect.init(x: 0, y: 0, width: 100, height: 44)
    button.setTitle("✚", for: .normal)
    button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 30)
    button.setTitleColor(UIColor.darkGray, for: .normal)
    button.addTarget(self, action: #selector(handle(sender:)), for: .touchUpInside)

    self.tableView.tableFooterView = button
}

和相关函数:

func handle(sender: UIButton) {
    print("Tapped")
}

结果如下:

另一种方式!我们可以使用UITableViewDelegate来实现。这是下面的示例,我们是如何完成的。

    override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {

        let button = UIButton.init()
        button.frame = CGRect.init(x: 0, y: 0, width: 100, height: 44)
        button.setTitle("✚", for: .normal)
        button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 30)
        button.setTitleColor(UIColor.darkGray, for: .normal)
        button.addTarget(self, action: #selector(handle(sender:)), for: .touchUpInside)

        return button
    }

    override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 44
    }


    func handle(sender: UIButton) {
        print("Tapped")
    }

注意:第二个选项在主屏幕上始终可见,如 header。