Swift-将左边框添加到UITableViewCell

Swift-将左边框添加到UITableViewCell,swift,Swift,我试图以编程方式设置每个表视图单元格的左边框。我使用UIView作为边框,但由于某些原因,我无法显示UIView。我还应该如何设置UIView高度?多谢各位 class Cell: UITableViewCell { var borderLeft: UIView = { let view = UIView() view.frame.size.width = 3 view.frame.size.height = 20 vie

我试图以编程方式设置每个表视图单元格的左边框。我使用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")
    }

}

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

borderLeft.rightAnchor.constraint(equalTo: self.rightAnchor, constant: 0).isActive = true
尝试使用
bottomAnchor
进行交换,例如:

borderLeft.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0).isActive = true
还添加宽度和高度的约束(请删除帧大小调整,因为它被视图忽略。translatesAutoResizezingMaskinToConstraints=false)

结果如下:


边框可能会隐藏在
contentView
backgroundView
下。您应该将所有自定义视图添加到其中一个视图中。谢谢您的回复!我在self.backgroundColor=.black之前添加了clipsToBounds,并更改了错误,但仍然是相同的。ok,已编辑,缺少对宽度和高度的约束。我在上面添加了一条评论。现在可以了!我所需要的只是锚。非常感谢。你能提供完整的代码吗?我得到一个错误线程1:致命错误:init(编码器:)尚未实现
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