2017-08-26 67 views
0

我想按照這個圓標籤和按鈕的三個角: rounded button拐角不是圓形的UILabel和UIButton的IOS迅速

但結果是:

Image of issue

一些角落的標籤是四捨五入的,有些不是。類似的,它發生的按鈕和寬度超過了按鈕走出tableview。

這是我使用的擴展代碼:

extension UIButton{ 
    func roundedButton(){ 
     let maskPAth1 = UIBezierPath(roundedRect: self.bounds, 
            byRoundingCorners: [.topLeft, .bottomLeft, .bottomRight], 
            cornerRadii:CGSize(width:8,height:8)) 
     let maskLayer1 = CAShapeLayer() 
     maskLayer1.frame = self.bounds 
     maskLayer1.masksToBounds=true 
     maskLayer1.path = maskPAth1.cgPath 
     self.layer.mask = maskLayer1 

    } 
} 

extension UILabel{ 
    func roundedLabel(){ 
     let maskPAth1 = UIBezierPath(roundedRect: self.bounds, 
            byRoundingCorners: [.topRight,.bottomRight,.bottomLeft], 
            cornerRadii:CGSize(width:10,height:10)) 
     let maskLayer1 = CAShapeLayer() 
     maskLayer1.frame = self.bounds 
     maskLayer1.cornerRadius=5 
     maskLayer1.masksToBounds=true 
     maskLayer1.path = maskPAth1.cgPath 
     self.layer.mask = maskLayer1 

    } 
} 

我打電話

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {} 
+0

在iOS中製作圓角很容易。所有你需要的是'view.layer.cornerRadius = aFloat'。沒有必要繼承任何東西,它適用於'UIView'的所有子類' –

+0

[在Rift中使用UIRectCorner的圓角矩形不能正常工作]的可能的重複(https://stackoverflow.com/questions/33050585/rounded-rect-using-u- directcorner在迅速不工作) –

回答

1

這些功能,這是因爲這些標籤和按鈕的bounds是最有可能不同,當你調用rounded...()方法以及它們何時呈現在表格視圖中。

這是因爲用於創建UIBezierPathbounds值與這些視圖在顯示在單元中後的值不同。表視圖佈局一個單元格,如果你創建的CAShapeLayer超出了它的界限,它會被「切斷」。

您應該創建一個UIButtonUILabel的子類,以便在每次佈局時更新其掩碼的貝塞爾路徑。

class RoundedLabel: UILabel { 

    override func layoutSubviews() { 
     super.layoutSubviews() 

     let maskPath = UIBezierPath(roundedRect: bounds, 
            byRoundingCorners: [.topRight, .bottomRight, .bottomLeft], 
            cornerRadii: CGSize(width: 10, height: 10)) 

     let maskLayer = CAShapeLayer() 
     maskLayer.frame = bounds 
     maskLayer.cornerRadius = 5 
     maskLayer.masksToBounds = true 
     maskLayer.path = maskPath.cgPath 
     layer.mask = maskLayer 
    } 
} 

至於進一步的優化,你可以懶洋洋地初始化掩膜層(意思是當它首次訪問將被創建),只有改變它在layoutSubviews方法框架和路徑。

class RoundedLabel: UILabel { 

    private lazy var maskLayer: CAShapeLayer = { 
     let maskLayer = CAShapeLayer() 
     maskLayer.cornerRadius = 5 
     maskLayer.masksToBounds = true 
     self.layer.mask = maskLayer 

     return maskLayer 
    }() 

    override func layoutSubviews() { 
     super.layoutSubviews() 

     let maskPath = UIBezierPath(roundedRect: bounds, 
            byRoundingCorners: [.topRight, .bottomRight, .bottomLeft], 
            cornerRadii: CGSize(width: 10, height: 10)) 

     maskLayer.path = maskPath.cgPath 
     maskLayer.frame = bounds 
    } 
} 
+0

awsome,它的作品像一個魅力^ _ ^非常感謝。 –