2016-03-02 62 views
0

我有下面的代碼UICollectionView的幾個要素:斯威夫特/重構屬性

cell.eventsImageView.clipsToBounds = true 
    cell.eventsImageView.layer.cornerRadius = 10.0 
    cell.eventsImageView.layer.borderWidth = 4.0 
    cell.eventsImageView.layer.borderColor = UIColor.uIColorFromHex(0xE90289).CGColor 

什麼是重構,最好的做法是什麼?

我想要做的事,如:

class refactoredXY (Bool, Double, Double, CGColor) { 
     clipsToBounds = Bool 
     cornerRadius = Double 
     borderWidth = Double 
     borderColor = CGColor 
    } 

要撥打:

cell.eventsImageView.refactoredXY(true, 10.0, 4.0, UIColor.uIColorFromHex(0xE90289)) 

回答

1

既然你實際修改的UIImageView屬性,你可以去Extension,在這裏您將添加功能,即做你需要的。像這樣

extension UIImageView { 
    func setDesiredProperties(clipsToBounds clipToBounds : Bool, layerCornerRadius : CGFloat, layerBorderWidth : CGFloat, layerBorderColor : UIColor) { 
     self.clipsToBounds = clipToBounds; 
     self.layer.cornerRadius = layerCornerRadius; 
     self.layer.borderWidth = layerBorderWidth; 
     self.layer.borderColor = layerBorderColor.CGColor; 
    } 
} 

然後,你可以簡單地調用它

cell.eventsImageView.setDesiredProperties(true, 10.0, 4.0, UIColor.uIColorFromHex(0xE90289)); 

另外,如果你想要這個功能是隻爲你的細胞可並不是所有UIImageView S,你可以把它這樣

extension YourCollectionViewCellClass { 
    func setDesiredProperties(clipsToBounds clipToBounds : Bool, layerCornerRadius : CGFloat, layerBorderWidth : CGFloat, layerBorderColor : UIColor) { 
     self.eventsImageView.clipsToBounds = clipToBounds; 
     self.eventsImageView.layer.cornerRadius = layerCornerRadius; 
     self.eventsImageView.layer.borderWidth = layerBorderWidth; 
     self.eventsImageView.layer.borderColor = layerBorderColor.CGColor; 
    } 
} 

,並應用這種方式

cell.setDesiredProperties(true, 10.0, 4.0, UIColor.uIColorFromHex(0xE90289)); 
+1

這些輸入變量是錯誤的:實際上cornerRadius與double不兼容,它是一個CGFloat值,對於borderWidth也是一樣。 –

+0

@AlessandroOrnano是的,錯過了。 Thanx爲了指出這一點 –

+0

謝謝你的幫助和偉大的解釋。 –