【问题标题】:Swift extend UIView to return calling typeSwift 扩展 UIView 以返回调用类型
【发布时间】:2021-05-25 20:59:37
【问题描述】:

我想扩展我在该对象上工作的基类 (UIView) 并返回具有正确类型的调用对象

extension UIView {
    func withCleanBg() -> UIView {
        self.backgroundColor = .clear
        return self;
    }
}

例如,如果我调用 let btn:UIButton = UIButton().withCleanBg(),我希望 btn 在调用扩展后保持 UIButton 而不是 UpCasted。

我希望它链接函数调用,例如 UIButton().withCleanBg().withFillInParent()等等

【问题讨论】:

  • 与您的问题无关,但考虑到没有参数,您应该使用计算属性而不是 e 函数

标签: ios swift generics uikit


【解决方案1】:

返回Self作为类型:

func withCleanBg() -> Self {

【讨论】:

    【解决方案2】:

    您可以返回Self 并使用@discardableResult 属性,因此无需关心返回。更多关于@discardableResult

    extension UIView {
        @discardableResult
        func withCleanBg() -> Self {
            self.backgroundColor = .clear
            return self
        }
        
        @discardableResult
        func withThemeCorner() -> Self {
            self.layer.cornerRadius = 10
            return self
        }
        
        @discardableResult
        func withFillInParent() -> Self {
            // Do your code here
            return self
        }
    }
    

    例子:

    UIButton().withCleanBg().withFillInParent() // Now this will not give warning like "Result of call to 'withFillInParent()' is unused"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-15
      • 1970-01-01
      相关资源
      最近更新 更多