Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ClipsToBounds is not working in cells

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).

like image 881
lithium Avatar asked Dec 08 '22 17:12

lithium


2 Answers

You should set the clipsToBounds property of the higher level container view (like the contentView of your cell.)

like image 114
M. Porooshani Avatar answered Jan 11 '23 01:01

M. Porooshani


Apply imageView.layer.maskToBounds = YES;

Apply this to view or imageview on which you want to set corner radius.

As you have mentioned corner radius to your view you need to set this for your view

like image 36
vivek bhoraniya Avatar answered Jan 11 '23 01:01

vivek bhoraniya