如何覆盖此类函数?

时间:2017-10-13 11:10:53

标签: ios swift3 uibutton swift-extensions

我有一个扩展类,我在下面扩展UIButton,它工作正常。

extension UIButton {    
    class func backButtonTarget(_ target: Any, action: Selector) -> UIBarButtonItem {        
        let backButton = UIButton(frame: CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(58), height: CGFloat(15)))
        backButton.setTitle("Cancel",for: .normal)
        let barBackButtonItem = UIBarButtonItem(customView: backButton)
        backButton.addTarget(target, action: action, for: .touchUpInside)
        return barBackButtonItem
    }
}

但是现在,我需要更改某个视图控制器的标题,所以我在考虑它的重写,但失败了。怎么可以覆盖它,以便我可以更改其title

2 个答案:

答案 0 :(得分:2)

扩展程序不能/不应该覆盖。

无法覆盖扩展中的功能(如属性或方法),如Apple的Swift指南中所述。

扩展程序可以为类型添加新功能,但它们无法覆盖现有功能。

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Extensions.html

您可以将栏按钮项子类化为

class CustomBarButtonItem: UIBarButtonItem {

      override func awakeFromNib() {
      super.awakeFromNib()
      customize()
     }

     func customize() {
         frame = CGRect(x: CGFloat(0), y:    CGFloat(0), width: CGFloat(58), height: CGFloat(15))
         // Add more as per requirement
     }

}

答案 1 :(得分:1)

为该函数设置title String参数,以便您可以调用它并提供自定义标题。

class func backButtonTarget(_ target: Any, action: Selector, title: String) -> UIBarButtonItem {
        let backButton = UIButton(frame: CGRect(x: 0, y: 0, width: 58, height: 15))
        backButton.setTitle(title, for: .normal)
        let barBackButtonItem = UIBarButtonItem(customView: backButton)
        backButton.addTarget(target, action: action, for: .touchUpInside)
        return barBackButtonItem
    }
}