1

I'm trying to set left border to each table view cell programmatically. I'm using UIView as a border but I cannot display the UIView for some reason. Also how should I set the UIView height? Thank you.

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
  • border will be probably hidden under the contentView or under the backgroundView. You should add all custom views to one of them. Commented Dec 17, 2017 at 7:41

1 Answer 1

1

I think there is a mistake on this anchor:

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

try instead to swap with bottomAnchor, like:

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

also add constraints for width and height (please remove frame resizing since is being ignored by 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

here the result:

enter image description here

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for your reply! I added clipsToBounds before self.backgroundColor = .black and changed the mistake but still the same.
ok, edited, was missing constraint on width and height. I added a comment above.
It works now! All I needed was widthAnchor. Thank you so much.
Can you provide the full code? I get the error Thread 1: Fatal error: init(coder:) has not been implemented

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.