【问题标题】:Custom UITableViewCell from XIB: contentView width is always the same来自 XIB 的自定义 UITableViewCell:contentView 宽度始终相同
【发布时间】: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


    【解决方案1】:

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

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

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

    【讨论】:

    • 谢谢,不知道这些。但是计算cellForRowAtIndexPath 的宽度是什么意思?为什么UITableViewCell 不自动具有tableView 的宽度?
    • UITableViewCell 根据您的约束获取宽度,但在调用 awakeFromNib 之后。所以在awakeFromNib你不会得到正确的框架!!!
    【解决方案2】:

    Swift 4+

    您可以使用以下代码,它将设置XIB单元格的框架,您还可以借助XIB高度和宽度调整内容。

    let cellRect = CGRect(x: 0, y: 0, width: postTableView.frame.size.width, height: imageHeight)
    cell?.frame = cellRect
    

    希望它会起作用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多