UITableViewCell上2个UILabel的布局

时间:2019-10-12 20:29:58

标签: ios swift uitableview uistackview

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

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

enter image description here

enter image description here

enter image description here

enter image description here

编辑: 。添加更多详细信息。我更新了UIStackView上的分发以平等地填充,并更新了第二个标签的对齐方式,即开始时间标签在右边。我现在在单元格上看到数据,但是第二个标签未正确对齐。

enter image description here

enter image description here cellForRow中的代码:

if

修改后的外观如下:

enter image description here

3 个答案:

答案 0 :(得分:2)

故事板解决方案:

您可以选择StackView的分布,使其在情节提要中具有相等的间距,并使用默认间距值。之后,标签仅需要高度约束(或者您可以为StackView设置高度),并将其放置在StackView的侧面。

Resulting cell

标签中的文本对齐方式无关紧要,因为标签仅会根据需要设置宽度。

答案 1 :(得分:1)

我没有使用太多的故事板,但是我知道这很有用。 首先,您必须在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: self.centerYAnchor, constant: 0),
            startLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 15),

            timeLabel.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -15),
            timeLabel.centerYAnchor.constraint(equalTo: self.centerYAnchor, constant: 0),
        ])

        self.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
    }

答案 2 :(得分:-1)

过去,我遇到过类似的问题,这是我找到的最佳解决方案,可以为标签(蓝色,红色)和StackView(黑色)分配BackgroundColor。然后,我看问题是否出在约束或UILabel文本对齐属性上。

此外,我注意到您对UIViews进行了扩展,其中可能存在引起问题的内容。