UIImageView hiding in Xcode8 and Swift3

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

I heard that this is either a Swift 3 or Xcode 8 problem (which makes sense because I now have this problem after the upgrade). I had the same problem with UIImageView and I found that the reason it was hiding was due to the fact that I called it too early in the loop. Since the last update, if I try to access @IBOutlet from nib, I can only do this in the viewDidAppear method. If I try to use the viewDidLoad or viewWillLoad method, then the output will be hidden.

In this case, I just change the UIImageView from square to circle through the following two lines of code:

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

Again, this only works with the vieDidAppear method. Is there a viewDidAppear method for a UITableViewCell? I put the same two lines in 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 awakeFromNib method of the cell, 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 greatly appreciated, thanks everyone!

Greetings

WITH

+4
source share
1 answer

You call it too soon. pictureImageViewnot yet known width. You need to call layoutIfNeeded:

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

A circle:

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

Source: https://habr.com/ru/post/1655660/


All Articles