我有一个简单的表格视图,我可以改变单元格的颜色,但是当试图改变表格视图(背景部分)的颜色时,它不起作用......我通过故事板尝试了...有人可以请帮助
首先在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()
}
for change 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(如默认(透明))放在SB中,并放在awakeFromNib中的Cell方法中,只需:
self.backgroundColor = UIColor.SomeColor