-2

I used this code to make UIImageView in a custom UITableViewCell, but the circular shape isn't updated until i pressed on the table cell, I tried the code in both awakeFromNib() and layoutSubviews()

  userImage.layer.cornerRadius = userImage.frame.size.width / 2
  userImage.layer.masksToBounds = true
  userImage.layer.borderColor = UIColor.black.cgColor
  userImage.layer.borderWidth = 1
  • add `userImage.clipToBounds = true` – Jawad Ali May 30 '20 at 15:03
  • 2
    [`layoutSubviews`](https://developer.apple.com/documentation/uikit/uiview/1622482-layoutsubviews) is definitely the right place to do this. Not `awakeFromNib`. The best place to do this is in a `UIImageView` subclass (e.g. https://stackoverflow.com/a/46530486/1271826). Then, whenever you need circular image view, just use this subclass, and you get the desired behavior with no extra code. – Rob May 30 '20 at 15:21

3 Answers3

0

You simply have to override the layoutSubviews() method of your UITableViewCell subclass, as it will be called on drawing updates.

Then just set your UIImageView's cornerRadius as you like:

class MyCustomTableViewCell: UITableViewCell {

    private let circularImageView: UIImageView = {
        $0.contentMode = .scaleAspectFill
        $0.layer.masksToBounds = true
        $0.layer.borderColor = UIColor.black.cgColor
        $0.layer.borderWidth = 1
        return $0
    }(UIImageView())

    // ...

    override func layoutSubviews() {
        super.layoutSubviews()
        circularImageView.layer.cornerRadius = circularImageView.frame.size.width/2
    }
}
0

if you create you tableviewCell programmatically you have to override init

override init(style: UITableViewCell.CellStyle,   reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier:  reuseIdentifier)
//put your code here
}
-2

update the imageViews cornerRadius just after a little time. Because frame.size.width / 2 will be different at runtime :

    DispatchQueue.main.asyncAfter(deadline : .now() + 0.05 {
  self.userImage.layer.cornerRadius = userImage.frame.size.width / 2
  self.userImage.layer.masksToBounds = true
  self.userImage.layer.borderColor = UIColor.black.cgColor
  self.userImage.layer.borderWidth = 1

}
Selçuk Yıldız
  • 539
  • 1
  • 5
  • 14
  • Using an arbitrary delay is not advisable. You risk having a flicker as the corner radius is applied (or missing it altogether). The [`layoutSubviews`](https://developer.apple.com/documentation/uikit/uiview/1622482-layoutsubviews) is designed for this use-case. – Rob May 30 '20 at 15:27
  • no there won't be any flicker. you can not see 0.05 second with eye. I have tried this a lot of apps and it works good. Maybe not the best option but straightforward solution. deserves to be downvoted but this works without any problem – Selçuk Yıldız May 30 '20 at 17:47