Clayton Andrew Cohn Clayton Andrew Cohn - 2 months ago 32
iOS Question

UIImageView gets hidden in Xcode8 and Swift3

My problems is simple: My @IBOutlet UIImageView in my custom UITableViewCell gets hidden if I try to access it via the cellForRowAtIndexpath method.

I've heard that this is either a Swift 3 or Xcode 8 problem (which makes sense because I just now have this problem after updating). I had the same problem with a UIImageView and discovered that the reason it was getting hidden was because I was calling it too early in the cycle. Since the latest update, if I try to access an @IBOutlet from the nib, I can only do so in the viewDidAppear method. If I try in the viewDidLoad or viewWillLoad method, then the outlet gets hidden.

In this case, I am simply changing a UIImageView from a square to a circle via the following two lines of code:

cell.pictureImageView.layer.cornerRadius = cell.pictureImageView.frame.size.width / 2;
cell.pictureImageView.clipsToBounds = true;


Again, this works only the vieDidAppear method. Is there a viewDidAppear method for a UITableViewCell? I put the same two lines in the cellForRowAtIndexPath and the image goes away:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: K.Cell, for: indexPath) as! TimelineTableViewCell

//Turn profile picture into a circle
cell.pictureImageView.layer.cornerRadius = cell.pictureImageView.frame.size.width / 2;
cell.pictureImageView.clipsToBounds = true;

return cell
}


I also tried it in the custom cell's awakeFromNib method and the same thing happened...the image disappears:

override func awakeFromNib() {
super.awakeFromNib()
cell.pictureImageView.layer.cornerRadius = cell.pictureImageView.frame.size.width / 2;
cell.pictureImageView.clipsToBounds = true;

}


Any help is much appreciated, thanks everyone!

Cheers,

C

Answer

You are calling it too early. pictureImageView has no known width yet. You need to call layoutIfNeeded:

cell.pictureImageView.layoutIfNeeded()
cell.pictureImageView.layer.cornerRadius = cell.pictureImageView.frame.size.width / 2
cell.pictureImageView.clipsToBounds = true

The circle is:

    init    
    UIViewController awakeFromNib
    loadView  // your pictureImageView is loaded here
    UIView awakeFromNib
    UIViewController viewDidLoad
    viewWillAppear 
    viewDidAppear // the properties of your pictureImageView are available here