[英]Why section header always showing in grey colour and in one line? in Swift
我並排使用兩個表格視圖,因此需要兩行黑色的 header 部分文本。 但它不會那樣......為什么?
代碼:我已經使用了這些方法,但仍然沒有以黑色和兩行顯示 header 文本...請告訴我,如何以黑色和兩行顯示 header 文本
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
35
}
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
(view as! UITableViewHeaderFooterView).textLabel?.textColor = UIColor.black
(view as! UITableViewHeaderFooterView).textLabel?.numberOfLines = 2
}
func numberOfSections(in tableView: UITableView) -> Int {
if tableView == tableView1 {
return nonProSubategory.count
} else if tableView == tableView2 {
return proSubategory.count
}
return 0
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if tableView == tableView1 {
return nonProSubategory[section].title
} else if tableView == tableView2 {
return proSubategory[section].title
}
return ""
}
o/p:此代碼文本始終以灰色顯示在一行中.. 這里“美容、健康..”和“家庭服務”是 header 文本
編輯:
如果我只使用這兩種方法:
func numberOfSections(in tableView: UITableView) -> Int {
if tableView == tableView1 {
return nonProSubategory.count
} else if tableView == tableView2 {
return proSubategory.count
}
return 0
}
private func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let v = UILabel()
v.textColor = .black
v.numberOfLines = 2
// you can set a font here, if desired
// for example:
//v.font = .italicSystemFont(ofSize: 15)
if tableView == tableView1 {
v.text = nonProSubategory[section].title
} else if tableView == tableView2 {
v.text = proSubategory[section].title
}
return v
}
o/p:這里缺少 header title("beauty,health.." and "home services")..
你可以采取你的方法......但是......
首先,您應該始終正確地轉換類並解開可選項:
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
if let v = view as? UITableViewHeaderFooterView,
let label = v.textLabel
{
label.textColor = .black
label.numberOfLines = 2
}
}
不過,默認的.textLabel
已被棄用,而且我認為.numberOfLines
不會起作用。
更好的方法是為 header 部分返回您自己的視圖。
此示例使用UILabel
作為要返回的視圖,但如果您願意,可以返回帶有各種子視圖的更復雜的視圖:
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let v = UILabel()
v.textColor = .black
v.numberOfLines = 2
// you can set a font here, if desired
// for example:
//v.font = .italicSystemFont(ofSize: 15)
if tableView == tableView1 {
v.text = nonProSubategory[section].title
} else if tableView == tableView2 {
v.text = proSubategory[section].title
}
return v
}
然后擺脫titleForHeaderInSection
, willDisplayHeaderView
和heightForHeaderInSection
(高度將被處理為自動布局)。
有多種方法可以將節標題添加到表視圖中,例如將其放在 UITableView 中,如果它在故事板中的 UIViewController 中或在像筆尖這樣的外部自定義視圖中。 包括你是如何在代碼中添加你的部分 header 的。 嘗試為此使用故事板和自動尺寸。 是的,如果需要,您可以限制行數。
一些樣品
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.