gpt4 book ai didi

ios - 来自 XIB : contentView width is always the same 的自定义 UITableViewCell

转载 作者:搜寻专家 更新时间:2023-10-31 22:59:10 26 4
gpt4 key购买 nike

我创建了一个带有 xib 文件的自定义 UITableViewCell。在那里我放置了几个标签和相对于 contentView 宽度的 View 。不幸的是,无论选择哪种设备,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 类中,我打印出内容 View 的宽度属性:

   override func awakeFromNib() {
super.awakeFromNib()

print("self.contentView.bounds.width: \(self.contentView.bounds.width)")
}

这总是打印出在 Interface Builder 中设置的宽度,即使它应该遵循使用 AutoLayout 的 tableView 的宽度:

enter image description here

尝试在返回前设置单元格的框架无效:

    cell.frame = CGRectMake(0, 0, self.tableView.frame.size.width, 71)

最佳答案

如果您正在使用 autolayout,那么在 cellforrowAtindexpath 中计算您的 width,您将获得合适的宽度。 awakeFromNib 在您的单元格获得自动布局之前被调用,因此它提供与 interface builder 中设置相同的宽度。

第二件事,如果您使用自动布局,那么设置 frame 没有任何意义。如果你想改变 height or width 那么你应该使用 outlet of your constraint (height or width) 你可以改变它的 constant 到想要的值(value)!

如果你只想改变高度,那么你可以使用 heightForRowAtIndexPathif else 来根据条件返回所需的高度!

关于ios - 来自 XIB : contentView width is always the same 的自定义 UITableViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39510892/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com