2017-09-07 66 views
-1

我正在以編程方式創建UILabel。但下面的代碼不會給我圓角。我想我錯過了一些非常基本的東西。UILabel swift的圓角

var textLabel:UILabel? = UILabel() 
textLabel?.text = text 
textLabel?.frame = CGRect(x:point.x, y:point.y, width:(textLabel?.intrinsicContentSize.width)!, height:15) 
textLabel?.backgroundColor = UIColor.white 
textLabel?.font = UIFont(name:"OpenSans", size:8) 
textLabel?.sizeToFit() 
textLabel?.layer.cornerRadius = 20.0 

任何人都可以請我指出正確的方向嗎?

+5

的可能的複製[如何做出的UIImage/- 查看帶有圓角的CGRect(SWIFT)](https://stackoverflow.com/questions/25476139/how-do-i-make -an-uiimage-view-with-rounded-corners-cgrect-swift) –

回答

6

,我認爲你應該爲textLabel設置maskToBounds。試試這個:

textLabel?.layer.masksToBounds = true 
1

設置masksToBounds爲您的標籤

masksToBounds作爲指示子層是否被剪切到圖層邊界布爾。

textLabel?.layer.cornerRadius = 20.0 
textLabel?.layer.masksToBounds = true 

參考蘋果documents

0

試試這個:

yourLabel.layer.cornerRadius = 8.0 
yourLabel.layer.masksToBounds = true 
yourLabel.layer.borderColor = UIColor.white.cgColor 
yourLabel.layer.borderWidth = 1.0 

這應該給你的圓角邊框

的關鍵是產權「maskToBounds」這是表示子層是否被剪切到圖層邊界布爾。

2

試試這個: -

textLabel?.layer.cornerRadius = textLabel?.frame.size.height/2.0 

textLabel?.layer.masksToBounds = true 
如果你想設置邊框顏色則

: -

textLabel?.layer.borderColor = .red.cgColor 
    textLabel?.layer.borderWidth = 1.0 
+0

提問者已經提到過尺寸'layer.cornerRadius = 20.0' –

+0

這是爲了當你想要準確的角落然後使用這個。如果尺寸大於或等於高度,則不會調整爲完美形狀。或者您可以根據需要使用常量值。 – Pushpendra