Swift - 向UITableViewCell添加左边框

问题描述 投票:1回答:1

我正在尝试以编程方式为每个表格视图单元格设置左边框。我使用UIView作为边框,但由于某种原因我无法显示UIView。另外我应该如何设置UIView高度?谢谢。

class Cell: UITableViewCell {

    var borderLeft: UIView = {
        let view = UIView()
        view.frame.size.width = 3
        view.frame.size.height = 20
        view.backgroundColor = .red
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()

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

        self.backgroundColor = .black

        addSubview(borderLeft)
        borderLeft.topAnchor.constraint(equalTo: self.topAnchor, constant: 0).isActive = true
        borderLeft.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 0).isActive = true
        borderLeft.rightAnchor.constraint(equalTo: self.rightAnchor, constant: 0).isActive = true

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
swift
1个回答
1
投票

我认为这个锚有一个错误:

borderLeft.rightAnchor.constraint(equalTo: self.rightAnchor, constant: 0).isActive = true

尝试改为与bottomAnchor交换,如:

borderLeft.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0).isActive = true

还添加了宽度和高度的约束(请删除帧大小调整,因为view.translatesAutoresizingMaskIntoConstraints = false会忽略它)

borderLeft.heightAnchor.constraint(equalToConstant: 20).isActive = true
borderLeft.widthAnchor.constraint(equalToConstant: 3).isActive = true
borderLeft.topAnchor.constraint(equalTo: self.topAnchor, constant: 0).isActive = true
borderLeft.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 0).isActive = true

结果如下:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.