2014-04-26 384 views
22

是否可以更改UISegmentedControl的拐角半徑?我嘗試了以下方法來改變UIView的圓角半徑。如何更改UISegmentedControl的圓角半徑?

self.segmentedControl.layer.cornerRadius = 15.0; 
    self.segmentedControl.layer.masksToBounds = YES; 

這不起作用,因爲你可以看到它只是切斷了UISegmentedControl的角落。 enter image description here

謝謝!

回答

66

這應該工作:

self.segmentedControl.layer.cornerRadius = 15.0; 
self.segmentedControl.layer.borderColor = [UIColor whiteColor].CGColor; 
self.segmentedControl.layer.borderWidth = 1.0f; 
self.segmentedControl.layer.masksToBounds = YES; 

您需要在設置cornerRadius後指定邊框。

+0

這是正確的解決方案! – rushelmet

+1

只有當你想增加角落角度時纔有效。 –

+4

它不能解決最初的問題,只有角落被切斷。請參閱下面的答案。 –

8

分段控制不會改變它繪製角的方式,所以它會繼續以自己的方式繪製角,然後將其切除。您不負責分段控制如何繪製其邊界形狀。如果你真的不喜歡它的繪製方式,你必須從頭開始設計自己的替代控制。你可以合理地接近你想要做的事情是設置分段控件的背景圖像。

4

你的結果是因爲別的東西(自定義繪圖?)控制邊框而不是圖層。幸運的是,該圖層設置似乎優先。

如果你知道你需要什麼邊框的顏色,你可以只添加(例如):

self.segmentedControl.layer.borderColor = [UIColor whiteColor].CGColor; 
self.segmentedControl.layer.borderWidth = 1.0; 
+0

它是如何改變圓角半徑的? –

+0

這不會改變拐角半徑。它只是補充問題中發佈的原始代碼以獲得預期結果。 –

1

使用下面的代碼:

segmentContrl.layer.borderColor=*anycolor*.CGColor; 
segmentContrl.layer.cornerRadius = 0.0; 
segmentContrl.layer.borderWidth = 1.5f; 
+0

沒有爲我工作 – longbow

+0

這通常會起作用。提供您的代碼,以便我可以查看它! –

+0

既不適合我也不適用 – iDev

31

將UISegmentedControl嵌入到UIView中並設置角落半徑爲UIView

目標C

outerView.layer.cornerRadius = CGRectGetHeight(outerView.bounds)/2; 
outerView.layer.borderColor = [UIColor blueColor].CGColor; 
outerView.layer.borderWidth = 1; 

夫特

outerView.layer.cornerRadius = CGRectGetHeight(outerView.bounds)/2 
outerView.layer.borderColor = UIColor.blueColor().CGColor 
outerView.layer.borderWidth = 1 

Cornered UISegmentedControl

+2

並且不要忘記在故事板 – Ilario

+0

中將剪輯子視圖添加到UIView,這是正確的解決方案 – Irfan

3

更新了夫特3 &的Xcode 8.2兼容性

mySegmentedControl.layer.cornerRadius = 25.0 
    mySegmentedControl.layer.borderColor = UIColor.white.cgColor 
    mySegmentedControl.layer.borderWidth = 1.0 
    mySegmentedControl.layer.masksToBounds = true 
2

以前的解決方案從來沒有爲我工作。我的解決方案是:

要將超級視圖中的UISegmentedControl嵌入,請將約束前導,尾隨,底部,頂部分配爲-1,以便切斷UISegmentedControl邊界。 最後應該這樣配置超級視圖:

segmentedControl.superview.clipsToBounds = true 
segmentedControl.superview.layer.cornerRadius = 0 //whatever 
segmentedControl.superview.layer.borderWidth = 1 
segmentedControl.superview.layer.borderColor = segmentedControl.tintColor.CGColor