【问题标题】:override UILabel setText: method in Swift覆盖 UILabel setText: Swift 中的方法
【发布时间】:2015-10-06 03:18:22
【问题描述】:

我确实遇到了一个问题,即我在带有 UILabel 子类的 iOS 中遇到了一些崩溃。现在我想覆盖setText: 来调用layoutIfNeeded,因为根据一些stackoverflow-answers (e.g. this one) 这可能会解决问题。

但是我怎样才能做到这一点呢?在 Objective-C 中这没什么大不了的,但我找不到在 Swift 中覆盖 setText: 的方法。

【问题讨论】:

    标签: swift ios7 uilabel


    【解决方案1】:

    覆盖text 属性并提供didSet 中的代码,当设置text 属性时,该代码将被执行:

    class MyLabel: UILabel {
         override public var text: String? {
            didSet {
                layoutIfNeeded()
            }
        }
    }
    

    【讨论】:

    • 正确答案在这里。比我快一分钟。 :)
    • @DanRosenstark 您是否在界面构建器和 swift 类上将您的 uilabel 更改为自定义 uilabel。通过这种方式,我可以覆盖设置文本方法。
    【解决方案2】:

    我从 Swift 2.0 中提取了 Method Swizzling。覆盖 UILabel 的 setText 方法。

    复制 app delegate 中的代码并使用 customSetText 进行应用级别的更改

       // MARK: - Method Swizzling
    
    extension UILabel {
        public override class func initialize() {
            struct Static {
                static var token: dispatch_once_t = 0
            }
    
            // make sure this isn't a subclass
            if self !== UILabel.self {
                return
            }
    
            dispatch_once(&Static.token) {
                let originalSelector = Selector("setText:")
                let swizzledSelector = Selector("customSetText:")
    
                let originalMethod = class_getInstanceMethod(self, originalSelector)
                let swizzledMethod = class_getInstanceMethod(self, swizzledSelector)
    
                let didAddMethod = class_addMethod(self, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))
    
                if didAddMethod {
                    class_replaceMethod(self, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod))
                } else {
                    method_exchangeImplementations(originalMethod, swizzledMethod)
                }
            }
        }
    
        // MARK: - Custom set text method for UI Label
    
        func customSetText(text: String) {
            self.customSetText(text)
            //set custom font to all the labels maintaining the size UILabel
            self.font = UIFont(name: "Lato-LightItalic", size: self.font.pointSize)
        }
    }
    

    【讨论】:

    • swift 4 不再支持public override class func initialize() 并抛出此错误:方法'initialize()' 定义了Objective-C 类方法'initialize',Swift 不允许这样做,知道如何将上述代码块转换为 swift 4 版本吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-07
    • 1970-01-01
    • 1970-01-01
    • 2015-03-26
    • 2016-05-31
    • 1970-01-01
    相关资源
    最近更新 更多