2017-08-10 85 views
0

我有一個來自類的視圖,我想將角半徑設置爲其寬度的一半。在視圖加載後在視圖中設置角點半徑

寬度是使用自動佈局製作的計算屬性。所以,一般情況下我設定的圓角半徑財產viewWillLayoutSubviews()像這樣

override func viewWillLayoutSubviews() { 
    super.viewWillLayoutSubviews() 

    c.largeProfileImage.layer.cornerRadius = c.largeProfileImage.frame.width/2 
} 

但largeProfileImage是不是被viewDidLoad中後稱爲初始視圖和動畫我它輕拍姿態。以下是視圖在屏幕上動畫的位置。它是在這個相同的功能中創建的。

 //I tried setting the cornerRadius here as well but it isn't setting. 

    //c.largeProfileImage.layer.cornerRadius = c.largeProfileImage.frame.width/2 


    self.view.layoutIfNeeded() 

    UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .curveEaseOut, animations: { 

     self.profileImageContainerCenterY?.constant = -(c.profileImageContainer.frame.height) * 2 
     self.profileSettingsContainerCenterY?.constant = 0 

     c.profileSettingsContainer.alpha = 1 
     c.largeProfileImage.alpha = 1 

     self.view.layoutIfNeeded() 
    }, completion: { (completed) in 
     self.view.layoutIfNeeded() 
}) 

編輯:

這裏的profileImage

let largeProfileImage: UIImageView = { 
    let pv = UIImageView() 
    pv.contentMode = .scaleAspectFill 
    pv.layer.masksToBounds = true 
    pv.clipsToBounds = true 
    pv.image = UIImage(named: "user") 

    pv.translatesAutoresizingMaskIntoConstraints = false 
    return pv 
}() 
+0

從類視圖添加視圖是在聲明類的相同控制器上?或者將控制器A中的類和控制器A中的類的視圖添加到控制器B中? –

+0

您是否嘗試在viewDidLayoutSubviews方法中添加cornerRadius?請嘗試使用這種方法,可能會在所有視圖佈局後幫助設置cornerRadius – 3stud1ant3

+0

您需要添加'largeProfileImage.layer.masksToBounds = false'和'largeProfileImage .clipsToBounds = true' – Annjawn

回答

1

我成功地調試了這個問題。

由於寬度爲一個計算的屬性是0的佈局被佈置意

c.largeProfileImage.layer.cornerRadius = c.largeProfileImage.frame.width/2 

self.view.layoutIfNeeded() 

導致零角半徑之前。

因此,解決辦法...

是調用它之後的寬度來設置轉角半徑的寬度計算之後。

self.view.layoutIfNeeded() 

c.largeProfileImage.layer.cornerRadius = c.largeProfileImage.frame.width/2 
0

爲了正確的動畫更改順序是這樣的。

self.profileImageContainerCenterY?.constant = -(c.profileImageContainer.frame.height) * 2 
    self.profileSettingsContainerCenterY?.constant = 0 
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .curveEaseOut, animations: { 
    c.profileSettingsContainer.alpha = 1 
    c.largeProfileImage.alpha = 1 
    self.view.layoutIfNeeded() 
}, completion: nil) 
+0

動畫很好,它會生成動畫。問題是拐角半徑未設置 – Stefan

+0

在設置拐角半徑後添加c.largeProfileImage.clipsToBounds = true。 –

+0

也爲什麼你要在完成處理程序中調用layoutIf。這不是必需的。 –

0

下三行是必要得到一個圓形圖像 -

image.layer.cornerRadius = image.frame.width/2 
image.layer.masksToBounds = false 
image.clipsToBounds = true 

您可能會看到一個圓形的UIImage但你也可能會發現圓內的圖像平方,解決你可能有玩contentMode。大部分時間.scaleAspectFill都能勝任。

+0

創建視圖時無法訪問自我...將在編輯中包含視圖。 – Stefan

+0

在你的更新中,它應該是'masksToBounds = false' – Annjawn

+0

我認爲這與我從類中獲取視圖並且沒有正確引用視圖有關。或者寬度是一個計算屬性的事實,當寬度等於0時,角半徑被設置。但是我不能在函數中調用viewWillLayoutSubviews。 – Stefan