如何在表格中显示自定义页脚视图?

时间:2018-08-31 05:19:47

标签: ios swift uitableview tablefooterview

我创建了一个UIviewXib,以将其显示在表格的页脚视图中。FooterView

import UIKit

/// This class is to display footer view in a settings table view
class FooterView: UIView {
    override func awakeFromNib() {
        super.awakeFromNib()
    }
}

我将其显示如下:

func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
    let view = FooterView(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 140))
    return view
}

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

这是怎么了?我看不到页脚视图,而在tableview行之间没有太多空间。

enter image description here

3 个答案:

答案 0 :(得分:3)

使用StoryBoard

UITableView中,您可以拖动UIView,如果原型单元格多于0,它将设置为FooterView。拖动后,您可以在表视图层次结构中将其视为子视图。现在,您可以在该视图上添加UILabel UIButton或任何组件,调整高度等。还可以在ViewController类文件中设置IBAction

以编程方式

let customView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
customView.backgroundColor = UIColor.red
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
button.setTitle("Submit", for: .normal)
customView.addSubview(button)

//Add that view in Table Footer View.
tableView.tableFooterView = customView // Here you can also use your xib View.

使用XIB

class MyClass: UIView {

    class func instanceFromNib() -> UIView {
        return UINib(nibName: "nib file name", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! UIView
    }
}

初始化视图并按如下所示使用它

let FooterView = MyClass.instanceFromNib()
tableView.tableFooterView = FooterView

enter image description here

输出:

enter image description here

答案 1 :(得分:1)

说明为什么有空白:这是由您的heightForFooterInSection方法引起的,它为footerView留了100个像素。不幸的是,您尚未为表View注册FooterView的Nib,并且它不知道在该位置要检索什么。

如何解决您的问题: 在您的ViewController中,需要注册供tableView使用的FooterView的笔尖。

E.G。:(请注意,您需要为footerView设置reuseIdentifier

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.register("FooterView", forHeaderFooterViewReuseIdentifier: "FooterView")
}

此后,您可以用与单元格类似的方式使footerView出队:

func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
    let footerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "FooterView")
    return footerView
}

答案 2 :(得分:0)

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

     let myFooter =  Bundle.main.loadNibNamed("ReportFooterCell", owner: self, options: nil)?.first as! ReportFooterCell

    myFooter.toWorkHours?.text = toWorkHour.toString()
    myFooter.workedHours?.text = workedHour.toString()

     return myFooter
}

func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
    return 40
}
相关问题