【发布时间】:2015-06-06 06:25:17
【问题描述】:
我有一个简单的表格视图,我可以更改单元格的颜色,但是当尝试更改表格视图(背景部分)的颜色时它不起作用...我通过 Storyboard 尝试过...有人可以请帮助
【问题讨论】:
标签: ios uitableview swift
我有一个简单的表格视图,我可以更改单元格的颜色,但是当尝试更改表格视图(背景部分)的颜色时它不起作用...我通过 Storyboard 尝试过...有人可以请帮助
【问题讨论】:
标签: ios uitableview swift
首先在viewDidLoad中设置tableView的背景色如下:
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.backgroundColor = UIColor.lightGrayColor()
}
现在添加这个方法:
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
cell.backgroundColor = UIColor.clearColor()
}
在 Swift 3 中,使用下面的方法而不是上面的方法:
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.backgroundColor = UIColor.lightGray
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.backgroundColor = UIColor.clear
}
【讨论】:
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
cell.contentView.backgroundColor = UIColor.yellowColor()
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.contentView.backgroundColor = UIColor.yellow
}
【讨论】:
使用此代码更改 tableView 颜色
override func viewDidLoad() {
super.viewDidLoad()
// define tableview background color
self.tableView.backgroundColor = UIColor.clearColor()
}
用于更改 tableView 单元格颜色
cell.backgroundColor = UIColor.clearColor()
【讨论】:
我玩游戏有点晚了!但是,以上答案都不适合我,所以只是分享一下我发现的东西,以防其他人跳上这个线程。
注意:我也有自己的自定义单元格类。不确定这是否会影响您的代码!
@IBDesignable class YourViewController: UITableViewController {
//IBInspectable and IBDesignable makes the properties accessible in storyboard
@IBInspectable var tableViewBackground: UIColor?
@IBInspectable var cellViewBackground: UIColor?
//in case you want to customize the text color, as well!
@IBInspectable var customTextColor: UIColor?
override func viewDidLoad() {
//your code
self.tableView.backgroundColor = tableViewBackground
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.textColor = customTextColor
cell.backgroundColor = cellViewBackground
return cell
}
//the rest of your code
}
查找您的可检查项:
1)。在 tableView 的 viewController 的 Storyboard 菜单中,单击 yourViewController。 viewController 中的第一个下拉菜单。 (第一个下拉菜单将包含您的 tableView 和 cellView。它还可以包含其他好东西,具体取决于您的特定项目)。
2)。在属性检查器中,您将看到一个标题,其中包含您的 viewController 名称和我们在上面定义的 @IBInspectable 属性!
3)。然后,您可以随心所欲地更改它们。
希望这会有所帮助!
【讨论】:
你有:
将 ContentView 像 Default(透明)一样放在 SB 中,并在 awakeFromNib 中的 Cell 的 Method 中,只需:
self.backgroundColor = UIColor.SomeColor
【讨论】: