Sergey Levkachev Sergey Levkachev - 3 months ago 14
Swift Question

Setting corner radius of an element in a custom UITableViewCell

My code is almost working, but there is one issue.

As soon as the table is loaded, images looks are as follows:

As soon as the table is loaded, images looks are as follows

But when i scroll the table everything is good:

But when i scroll the table everything is good

What is missing here?

class ShopTableViewCell: UITableViewCell {

let disposeBag = DisposeBag()

@IBOutlet weak var shopImageView: UIImageView!
@IBOutlet weak var imagesCollectionView: UICollectionView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var likeButton: UIButton!
@IBOutlet weak var imageContainer: UIView!

override func layoutSubviews() {
super.layoutSubviews()
imageContainer.clipsToBounds = true
imageContainer.layer.cornerRadius = imageContainer.frame.size.width / 2
imageContainer.layer.borderWidth = 1
imageContainer.layer.borderColor = UIColor(hex: "#BDBDBD").CGColor

Answer

It's because the frame property of your imageview is not updated yet.

You can make a subclass of UIImageView and do that job there, like:

Swift

class CircleImageView: UIImageView {

  override func layoutSubviews() {
    super.layoutSubviews()

    self.layer.borderWidth = 1 / UIScreen.mainScreen().scale
    self.layer.borderColor = UIColor(hex: "#BDBDBD").CGColor
    self.layer.cornerRadius = self.bounds.size.width/2
    self.layer.masksToBounds = true
  }
}

Objective-C

@implementation CircleImageView

- (void)layoutSubviews {
    [super layoutSubviews];

    self.layer.borderWidth = 1 / [UIScreen mainScreen].scale;
    self.layer.borderColor = [UIColor whiteColor].CGColor;
    self.layer.cornerRadius = self.bounds.size.width/2;
    self.layer.masksToBounds = YES;
}

@end