【发布时间】:2016-09-15 12:20:35
【问题描述】:
我用xib 文件创建了一个自定义UITableViewCell。在那里,我放置了几个相对于contentView 宽度的标签和视图。不幸的是,无论选择哪个设备,contentView.bounds.width 属性始终保持不变。
我的 ViewController 也是从 nib 加载的:
class ViewController: UIViewController {
@IBOutlet var tableView: UITableView!
init(title: String) {
super.init(nibName: "ViewController", bundle: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerNib(UINib(nibName: "CustomTableViewCell", bundle: nil), forCellReuseIdentifier: "CustomTableViewCell")
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CustomTableViewCell", forIndexPath: indexPath) as! CustomTableViewCell
return cell
}
}
在CustomTableViewCell 类中,我打印出内容视图的宽度属性:
override func awakeFromNib() {
super.awakeFromNib()
print("self.contentView.bounds.width: \(self.contentView.bounds.width)")
}
这总是会打印出 Interface Builder 中设置的宽度,即使它应该遵循使用 AutoLayout 的 tableView 的宽度:
在返回之前尝试设置单元格的框架无效:
cell.frame = CGRectMake(0, 0, self.tableView.frame.size.width, 71)
【问题讨论】:
标签: ios swift uitableview xib