Swift - 向UITableViewCell添加左边框

时间:2017-12-17 07:33:55

标签: swift

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

}

1 个答案:

答案 0 :(得分: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