简体   繁体   中英

Static cell at the bottom of a UITableView

I have a table view filled with contacts. At the very bottom of the table view (after the last contact) I would like to have a static table view cell that is always there with custom content.

How can I accomplish this?

Lets say that the array you are using to populate your UITableView is called 'contactsArray'.

What you would need to do in the following delegate method is add an additional row eg:

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

    return contactsArray+1

}

Then you would need to handle this logic eg:

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

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

Here's the example:

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
}

And associated function:

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

Here's the result:

在此处输入图片说明

Another way! We can implement by using UITableViewDelegate . And here's the example below, how we done.

    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")
    }

Note: Second option is always visible on the main screen like a section header.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM