【问题标题】:UITableViewCell is wider than its UITableView - extending to the right?UITableViewCell 比它的 UITableView 更宽 - 向右延伸?
【发布时间】:2019-01-29 06:41:01
【问题描述】:

背景

我有一个带有单个单元格的 UITableView。单元格内是UILabel。名为PickerTableViewCell 的单元格从xib 获取其UI 并将其添加到其子视图中。这样做是因为这个 xib 被许多不同的自定义单元格使用。

问题

当这个单元格被表格视图出列时,它的宽度似乎超出了右侧表格视图的宽度。

这是带有UILabel 在单元格中居中的xib,然后是它在设备上的显示方式。注意标签在设备上是如何偏离中心的:

当我将标签移动到单元格的最右侧 (label.trailing = pickerCell.trailing + 0) 时,它会从右侧消失。下面是它在 xib 中的外观以及它在设备上的外观:

当我将UILabel 对齐到单元格的左侧 (label.leading = pickerCell.leading + 0) 时,它正确地对齐到设备的左侧。

这是PickerTableViewCell 加载 xib 的方式:

override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)


        // load the xib to associate with
        let nib = Bundle.main.loadNibNamed("PickerTableViewCell", owner: nil, options: nil)
        if let view = nib?.first as? UIView{
            self.addSubview(view)
        }
    // ...
}

这是 tableview 注册单元格的方式:

self.tableView.register(PickerTableViewCell.self, forCellReuseIdentifier: "pickerCell")

最后是它的出队方式:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "pickerCell") as! PickerTableViewCell
        return cell
}

谁能帮助理解发生了什么?为什么我的单元格似乎超出了表格视图的宽度?

【问题讨论】:

  • 使用标签约束:top、bottom、leading、trailing = 0 with superview and do myLabel.textAlignment = .center

标签: ios swift xcode autolayout interface-builder


【解决方案1】:

在分配任何xib 时,您必须指定frame。这是修改后的代码:

override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)

    // load the xib to associate with
    let nib = Bundle.main.loadNibNamed("PickerTableViewCell", owner: nil, options: nil)
    if let view = nib?.first as? UIView{
        self.addSubview(view)
        view.frame = bounds //Provide the frame
    }
    // ...
}

【讨论】:

  • 不同意,这是post,SO 从 XIB 加载单元格,但没有人向单元格提供框架,这是可以理解的 为什么
  • 这完美解决了!我正在为此拉头发-谢谢!
  • @dahiya_boy 我不这么认为,试试你的情况并告诉我;)我在这里知道你的答案:D
  • @SohilR.Memon,我直接加载XIB并注册。我从来没有做过这种做法(添加为子视图),因为它从来都不是必需的,我不认为这是一个好的做法 bcz 你的 xib 是 UITableviewCell,当你使用 nib?.first 时,它会将单元格本身作为 UIView 所以为什么它需要添加为子视图。
  • @SohilR.Memon,我已经提到了单元格本身 UIView 和 OP 从 nib 向其中添加了一个视图,这对我来说是无法消化的。休息一下,每个人都有自己的风格代码,所以我不能再提交了。顺便说一句,感谢您的解释。
【解决方案2】:

如果使用 Nib 进行单元设计,请不要注册单元类本身,而是注册 nib。

删除代码

init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) 

注册过程是这样的

let cellNib = UINib.init(nibName: "YourNibName", bundle: nil)
tableView.register(cellNib, forCellReuseIdentifier: "Identifier")

出列过程没问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-17
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    • 1970-01-01
    • 1970-01-01
    • 2019-12-19
    • 1970-01-01
    相关资源
    最近更新 更多