![](/img/trans.png)
[英]swift change section array element text or font color in tableview header
[英]Swift: Changing TableView Header text color - Crashing
使用Swift 3,我試圖以編程方式更改Section的Header顏色。
如何改變的backgroundColor為白色,文本顏色為黑色?
該節頭改變顏色,但不顯示任何文本,然后當我添加代碼來改變它崩潰標題文字顏色
由於未捕獲的異常“ NSInvalidArgumentException”而終止應用程序,原因:“無法將自身添加為子視圖”
SWIFT代碼
// Title for Header
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
// Section Names
let sectionNames = ["Followed Blogs", "All Blogs"]
return sectionNames[section]
}
// View for Header
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView()
let headerLabel = UILabel()
let sectionNames = ["Followed Blogs", "All Blogs"]
headerLabel.text = sectionNames[section]
headerLabel.frame = CGRect(x: 45, y: 5, width: 100, height: 35)
headerLabel.addSubview(headerLabel)
if (section == 0) {
headerView.backgroundColor = UIColor.green
headerLabel.textColor = UIColor.black
} else {
if darkMode {
headerView.backgroundColor = UIColor.white
headerLabel.textColor = UIColor.black
} else {
headerView.backgroundColor = UIColor.black
headerLabel.textColor = UIColor.white
}
}
return headerView
}
// Height for Section
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 45
}
headerLabel.addSubview(headerLabel)
將標簽添加到self,這是錯誤的來源
根據我對代碼的理解,您可能應該改用headerView.addSubview(headerLabel)
文字“ Followed Blogs”不合適,顯示為“ Followed B ...”
(最可能是)布局問題,我將親自調查向標簽添加自動布局約束,以便將其綁定到父視圖的頂部/底部/左側/右側邊距
這只是補充MadProgrammer的答案。 我想不是UIView
你應該使用UITableViewHeaderFooterView
用法:
tableViewInstance.register(UITableViewHeaderFooterView.self, forHeaderFooterViewResuseIdentifier: "headerIdentifier")
然后在viewForHeaderInSection
:
let tableViewHeader = tableview.dequeueReusableHeaderFooterView(withIdentifier: "headerIdentifier")
順便說一句,因為您的標簽寬度對於當前字體而言太小,導致文本"Followed Blogs"
不適合其內容。 為什么不添加這樣的約束:
headerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-5-[label]-5-|",
options: [],
metrics: nil,
views: ["tableView": headerLabel]))
headerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-5-[label]-5-|",
options: [],
metrics: nil,
views: ["tableView": headerLabel]))
您使tableView的headerHeight是動態的
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.