2016-09-23 75 views
4

我的問題很簡單:我的自定義UITableViewCell中的@IBOutlet UIImageView被隱藏,如果我嘗試通過cellForRowAtIndexpath方法訪問它。UIImageView隱藏在Xcode8和Swift3中

我聽說這是一個Swift 3或Xcode 8問題(這是有道理的,因爲我剛纔更新後有這個問題)。我遇到了與UIImageView相同的問題,並發現它隱藏的原因是因爲我在循環中過早地調用它。自從最新更新以來,如果我嘗試從nib訪問@IBOutlet,我只能在viewDidAppear方法中這樣做。如果我在viewDidLoad或viewWillLoad方法中嘗試,那麼插座會隱藏起來。

在這種情況下,我只是通過代碼下面的兩行改變從正方形一個UIImageView到圈子:

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

再次,這僅適用的vieDidAppear方法。有沒有UITableViewCell的viewDidAppear方法?我把同樣的兩行的cellForRowAtIndexPath和圖像消失:

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 
} 

我也試了一下在自定義單元格的awakeFromNib方法,同樣的事情發生了......圖像中消失:

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

} 

任何幫助非常感謝,謝謝大家!

乾杯,

Ç

回答

2

你太早調用它。 pictureImageView還不知道width呢。 你需要調用layoutIfNeeded

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

圓是:

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

我知道我早調用它,這就是問題所在。高度和寬度都是在故事板中設置的,但如果我在cellForRow中進行設置,並在它自然調用之前實例化ImageView,則會丟失imageview的所有其他預設屬性。我的問題是**,當*,在循環中,imageview是否被實例化...即,它是什麼方法,所以我可以訪問它。 –

+0

請參閱我的編輯。也許這有助於你? –

+0

調用layoutIfNeeded,你可以像viewDidAppear –