ClipsToBounds is not working in cells

Viewed 6090

I have an UITableView with custom cells. The structure of every cell is like that: I have contentView, in this contentView I have backView (simple UIView with white background and cornered radius 16.0), in this backView I have an imageView with some picture.

What I want is to have this imageView cornered (within his parent UIView — backView — borders). And it doesn't work this way.

The code is quite simple (from ImageCell.swift):

    self.backView = UIView()
    self.backView.backgroundColor = UIColor.white
    self.backView.translatesAutoresizingMaskIntoConstraints = false
    self.backView.layer.cornerRadius = 16.0
    self.contentView.addSubview(backView)

    self.picture = UIImageView()
    self.picture.translatesAutoresizingMaskIntoConstraints = false
    self.picture.contentMode = UIViewContentMode.scaleAspectFill
    self.picture.backgroundColor = UIColor.gray
    self.picture.clipsToBounds = true
    self.backView.addSubview(picture)

    let constraintPicTop = NSLayoutConstraint(item: picture, attribute: .top, relatedBy: .equal, toItem: contentView, attribute: .topMargin, multiplier: 1.0, constant: -6)
    let constraintPicLeft = NSLayoutConstraint(item: picture, attribute: .left, relatedBy: .equal, toItem: backView, attribute: .leftMargin, multiplier: 1.0, constant: -8)
    let constraintPicRight = NSLayoutConstraint(item: picture, attribute: .right, relatedBy: .equal, toItem: backView, attribute: .rightMargin, multiplier: 1.0, constant: 8)
    constraintBottomPic = NSLayoutConstraint(item: picture, attribute: .bottom, relatedBy: .lessThanOrEqual, toItem: contentView, attribute: .topMargin, multiplier: 1.0, constant: 150)

I don't know the size of the image beforehand, so constraintBottomPic value is updating in cellForRowAt function.

And it's working except this image is not cornered (and I believe it should be).

(It's not possible for me to set cornerRadius for UIImageView unfortunately).

update: Found the solution. It seems I had to set 'clipsToBounds' to true in all the parent views directly (contentView and backView, in my case).

2 Answers
Related