繁体   English   中英

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

[英]How to display custom footer view in table?

我创建了一个UIviewXib我的表中的页脚视图来显示它。 页脚视图

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行之间没有太多空间。

在此处输入图片说明

使用StoryBoard

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

以编程方式

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

在此处输入图片说明

输出:

在此处输入图片说明

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

如何解决您的问题:在ViewController您需要注册FooterView的Nib以供tableView

EG :(请注意,您需要在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
}
 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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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