如何在UITableView中改变section头的颜色?
编辑:DJ-S提供的答案应该适用于iOS 6及以上版本。公认的答案已经过时了。
如何在UITableView中改变section头的颜色?
编辑:DJ-S提供的答案应该适用于iOS 6及以上版本。公认的答案已经过时了。
当前回答
使用RubyMotion / RedPotion,将其粘贴到你的桌面屏幕:
def tableView(_, willDisplayHeaderView: view, forSection: section)
view.textLabel.textColor = rmq.color.your_text_color
view.contentView.backgroundColor = rmq.color.your_background_color
end
效果好极了!
其他回答
swift 5 +
在willDisplayHeaderView方法中
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
//For Header Background Color
view.tintColor = .black
// For Header Text Color
let header = view as! UITableViewHeaderFooterView
header.textLabel?.textColor = .white
}
我希望这对你有所帮助:]
斯威夫特2
我成功地通过添加模糊效果改变了部分背景颜色(这真的很酷)。要轻松更改部分的背景颜色:
首先转到Storyboard并选择表视图 转到属性检查器 列表项 向下滚动到视图 改变“背景”
然后为模糊效果,添加到代码:
override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
// This is the blur effect
let blurEffect = UIBlurEffect(style: .Light)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
// Gets the header view as a UITableViewHeaderFooterView and changes the text colour and adds above blur effect
let headerView: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
headerView.textLabel!.textColor = UIColor.darkGrayColor()
headerView.textLabel!.font = UIFont(name: "HelveticaNeue-Light", size: 13)
headerView.tintColor = .groupTableViewBackgroundColor()
headerView.backgroundView = blurEffectView
}
基于@Dj的回答,使用Swift 3。这在iOS 10上运行得很好。
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
// Background color
view.tintColor = UIColor.black
// Text Color
let headerView = view as! UITableViewHeaderFooterView
headerView.textLabel?.textColor = UIColor.white
}
如果有人需要斯威夫特,请保留头衔:
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView(frame: CGRect(x: 0,y: 0,width: self.tableView.frame.width, height: 30))
view.backgroundColor = UIColor.redColor()
let label = UILabel(frame: CGRect(x: 15,y: 5,width: 200,height: 25))
label.text = self.tableView(tableView, titleForHeaderInSection: section)
view.addSubview(label)
return view
}
Although func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) will work as well, you can acheive this without implementing another delegate method. in you func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? method, you can use view.contentView.backgroundColor = UIColor.white instead of view.backgroundView?.backgroundColor = UIColor.white which is not working. (I know that backgroundView is optional, but even when it is there, this is not woking without implementing willDisplayHeaderView