UITableViewCell 上 2 个 UILabel 的布局

Layout for 2 UILabels on UITableViewCell

我希望在自定义 table 视图单元格上有 2 个标签。第一个标签应位于距左边距 15 点的左侧,第二个标签应位于距右边距 15 点的右侧。它可以在内部生长。由于标签不会显示大量数据,因此肯定不会相互重叠。

我正在使用堆栈视图。下面是我的自定义 xib 文件的图像。两个标签的行数都设置为 1。启动时,我看到一个没有标签的空白单元格。缺少什么?

编辑: 添加更多详细信息。我将 UIStackView 上的分布更新为 Fill Equally 并更新了第二个标签的对齐方式,即开始时间标签到右边。我现在看到单元格上的数据,但第二个标签没有正确对齐。

cellForRow 中的代码:

let cell = tableView.dequeueReusableCell(withIdentifier: "displayStartTime") as! ScheduleDisplayStartTimeCustomCell
cell.selectionStyle = UITableViewCell.SelectionStyle.gray
cell.titleLabel.text = "Start"
cell.timeLabel.text = startTime
return cell

这是编辑后的样子:

我过去遇到过类似的问题,我发现最好的解决方案是为标签(蓝色、红色)和 StackView(黑色)分配背景颜色。然后我看看问题是出在约束上,还是出在 UILabel 文本对齐属性上。

此外,我注意到您有 UIViews 的扩展,其中可能存在导致问题的原因。

我不经常使用故事板,但我知道这很管用。 首先,您必须在 viewDidLoad:

中注册单元格
tableView.register(ScheduleDisplayStartTimeCustomCell.self, forCellReuseIdentifier: "displayStartTime")

然后您可以像这样以编程方式创建自定义单元格:

class ScheduleDisplayStartTimeCustomCell: UITableViewCell {
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupView()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    let startLabel: UILabel = {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.numberOfLines = 1
        label.textAlignment = .left
        return label
    }()
    
    let timeLabel: UILabel = {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        label.numberOfLines = 1
        label.textAlignment = .right
        return label
    }()

    
    func setupView() {
        addSubview(startLabel)
        addSubview(timeLabel)
        
        NSLayoutConstraint.activate([
            startLabel.centerYAnchor.constraint(equalTo: centerYAnchor),
            startLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 15),
           
            timeLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -15),
            timeLabel.centerYAnchor.constraint(equalTo: centerYAnchor)
        ])
        
        selectionStyle = UITableViewCell.SelectionStyle.gray
    }
    
}

最后你会像这样设置你的单元格:

  override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "displayStartTime") as! ScheduleDisplayStartTimeCustomCell
        cell.startLabel.text = "Start"
        cell.timeLabel.text = startTime
        
        return cell
    }

故事板解决方案:

您可以 select StackView 的分布在情节提要中使用默认间距值等间距。 Labels 之后只需要高度限制(或者你可以为 StackView 设置高度),并将定位到 StackView 的两侧。

Resulting cell

Label 中的文本对齐无关紧要,因为 Label 的宽度将根据需要调整。