Ios UITableView背景色和UITableView.appearance
我正在尝试创建一个包含UITableView的简单视图。 我想通过表视图的backgroundColor属性将表视图的背景色更改为紫色。苹果文档中说,只需将backgroundView属性设置为nil,它就可以工作。就我而言,它不起作用 我必须调用UITableView.appearance().backgroundColor= UIColor.purpleColor()使其能够工作,而不仅仅是 UITableView.backgroundColor=UIColor.purleColor() 我的问题是为什么 代码如下:Ios UITableView背景色和UITableView.appearance,ios,uitableview,cocoa-touch,Ios,Uitableview,Cocoa Touch,我正在尝试创建一个包含UITableView的简单视图。 我想通过表视图的backgroundColor属性将表视图的背景色更改为紫色。苹果文档中说,只需将backgroundView属性设置为nil,它就可以工作。就我而言,它不起作用 我必须调用UITableView.appearance().backgroundColor= UIColor.purpleColor()使其能够工作,而不仅仅是 UITableView.backgroundColor=UIColor.purleColor() 我
class TaskTableView: UIView {
var tableView = UITableView(frame: CGRectZero, style: .Plain)
override init(frame: CGRect) {
super.init(frame: frame)
tableView.backgroundView = nil
tableView.backgroundColor = UIColor.purpleColor()
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
tableView.translatesAutoresizingMaskIntoConstraints = false
addSubview(tableView)
let views = ["table": tableView]
addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat("|[table]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)
)
addConstraints(
NSLayoutConstraint.constraintsWithVisualFormat("V:|[table]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)
)
}
required init?(coder aDecoder: NSCoder) {
fatalError()
}
}
在以编程方式创建新视图(自定义子类
TaskTableView
)时,上面提供的示例代码对我来说非常有用:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let tableViewFrame : CGRect = CGRectMake(20, 20, 100, 300)
let taskTableView : TaskTableView = TaskTableView.init(frame: tableViewFrame)
view.addSubview(taskTableView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
在空白的新项目中运行此代码时,使用问题中提供的TaskTableView的类定义,结果是具有所需紫色背景色的表视图
话虽如此,我可以猜出为什么您在设置表视图的背景色时遇到问题。该问题可能与视图生命周期有关。在视图出现在屏幕上之前,外观协议应用于视图。您可能在视图生命周期中过早地实例化自定义视图实例,即在视图的包含视图控制器从其nib唤醒之前。因此,您试图在尚未反序列化的视图上设置属性,因此不会显示所需的背景色设置。请参阅苹果开发者文档中的以下引用 如果您计划从nib文件加载自定义视图类的实例,您应该知道,在iOS中,nib加载代码不使用initWithFrame:方法来实例化新的视图对象。相反,它使用initWithCoder:方法,该方法是NSCoding协议的一部分 (参考资料:) 值得指出的是,UITableView类通常仅作为UIViewController的子视图添加,同一视图控制器还充当表视图的委托和数据源。Apple建议您使用其预配置的UITableViewController,它是一个UIViewController,以UITableView作为其视图,还充当数据源和委托。直接将UITableView添加为自定义视图类的子视图(如您所做)不是最佳做法,因此不鼓励这样做 有关使用UITableView类的更多信息,请参阅Apple官方文档: