[英]How to display custom footer view in table?
我創建了一個UIview
類Xib
我的表中的頁腳視圖來顯示它。
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.