2017-08-15 78 views
0

我有一個矩形視圖,我希望「完美」圓形邊框的兩端。我四捨五入的角落,像這樣:矩形視圖上的完美​​圓角

contentView.layer.cornerRadius = 30; //arbitrary number 

    contentView.layer.borderWidth = 1.0 
    contentView.layer.borderColor = UIColor.white.cgColor 

這是我的結果:

enter image description here

這是我的目標結果: enter image description here

我d喜歡爲我的視角確定cornerRadius以動態實現四捨五入的結束。有任何想法嗎?謝謝!

+3

你需要使cornerRadius等於高度的一半。 – rmaddy

+0

,你需要在佈局完成/更改時執行此操作,而不是在'viewDidLoad' /'init'中執行**。 – luk2302

+0

...例如在視圖控制器的['viewDidLayoutSubviews'](https://developer.apple.com/documentation/uikit/uiviewcontroller/1621398-viewdidlayoutsubviews)中(或者,如果在'UIView'子類中使用['layoutSubviews']( https://developer.apple.com/documentation/uikit/uiview/1622482-layoutsubviews))。 – Rob

回答

2

你是對的。有些傳統的方法做它看起來像這樣:

contentView.layer.cornerRadius = contentView.bounds.height/2 
+0

你可以在更多的上下文中放置代碼嗎? – luk2302

+0

我試過這個(實際上發佈問題之前)。我得到了一個非常時髦的結果http://imgur.com/5HYe8Fx.png – user1282637

+1

@ user1282637 *你*放置了哪些代碼? – luk2302

2

如果你的「內容查看」是從一個UIView然後繼承的類:

class CustomView: UIView 
{ 
    ... 
    override func layoutSubviews() 
    { 
     super.layoutSubviews() //Don't want to change the default behavior of this func. Just want to add to it. 
     layer.cornerRadius = bounds.height/2 
    } 
    ... 
} 

如果只是在一個UIViewController一個普通的UIView,然後你可以在UIViewController的viewWillAppear(_ animated:Bool)方法中更新它。