2017-10-14 71 views
1

我最近開始學習swift,並在swift 3中做類別。我在Viewcontroller A中添加了一個擴展,並添加了一個函數來刪除對象類CustomText.Now中的label.text,everythiing是做我唯一缺少的是對這個新擴展方法的調用。 下面是代碼:類別調用swift 3

ViewControllerA 

extension String { 
    func setLabelText(){ 
    let cell = ProductListingCell() 
    let text = CustomText() 
    cell.discountLabel.attributedText = text.getTextToStrikeThrough(label:cell.discountLabel) 
    } 

CustomText

func getTextToStrikeThrough(label:UILabel) -> NSAttributedString { 
    let attributeString: NSMutableAttributedString = NSMutableAttributedString(string:label.text!) 
    attributeString.addAttribute(NSStrikethroughStyleAttributeName, value: 2, range: NSMakeRange(0, attributeString.length)) 
    label.attributedText = attributeString 
    let str = label.attributedText 
    return str! 
} 

請幫助我明白這是如何擴展字符串應在功能帶來,讓調試器的推移它並執行所需task.Thanks提前!

+2

這不會真正爲你工作;你只是創建一個單元格的新實例並在其上設置一些文本。該單元不顯示在任何地方,只要函數退出,它就會被拋棄。如果你想做這個擴展,那麼它應該是'UILabel'上的擴展,然後你會說'someLabel.setStrikethroughText(myString)' – Paulw11

回答

0

你必須瞭解哪些擴展做,它們擴展一個基類,像提到的,你可以像這樣

extension UILabel { 
    func strikeThrough() { 
     let attribute = [NSAttributedStringKey.strikethroughStyle : 2] 

     let attributedString = NSAttributedString(string: self.text!, attributes: attribute); 

     self.attributedText = attributedString 
    } 
} 

然後你當你有一個UILabel你可以做

中添加附加的UILabel @ Paulw11
label.strikeThrough() 

或者你也可以擴展字符串,如:

extension String { 
    func strikeThroughAttributedString() -> NSAttributedString { 
     let attribute = [NSAttributedStringKey.strikethroughStyle : 2] 

     let attributedString = NSAttributedString(string: self, attributes: attribute); 

     return attributedString 
    } 
} 

,你可以使用像這樣:

label.attributedText = label.text!.strikeThroughAttributedString() 

我希望這將是怎樣的擴展,可以使用一個很好的例子

+0

讓我知道如果你有關於代碼的任何問題,我會很高興迴應 – Ladislav