【问题标题】:How To Create A Re-usable IBDesignable Code如何创建可重用的 IBDesignable 代码
【发布时间】:2019-02-27 13:03:07
【问题描述】:

在使用 IBDesignable 时,以下代码很常见,每次创建类时都会重复,有没有办法避免这种重复?

override init(frame: CGRect) {
    super.init(frame: frame)

    themeProp()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)

    themeProp()
}

override func prepareForInterfaceBuilder() {
    super.prepareForInterfaceBuilder()

    themeProp()
}

这就是我目前使用 IBDesignable 为 UIButton 创建样式的方式。

import UIKit

let colorWhite = colorLiteral(red: 0.9999127984, green: 1, blue: 0.9998814464, alpha: 1)
let colorLavender = colorLiteral(red: 0.6604440808, green: 0.5388858914, blue: 0.8827161193, alpha: 1)

@IBDesignable class PrimaryButtonA: UIButton {

    override init(frame: CGRect) {
        super.init(frame: frame)

        themeProp()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        themeProp()
    }

    func themeProp() {
        setTitleColor(colorWhite, for:.normal)
        self.layer.cornerRadius = 10
        backgroundColor = colorLavender
    }

    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()

        themeProp()
    }
}


@IBDesignable class PrimaryButtonB: UIButton {

    override init(frame: CGRect) {
        super.init(frame: frame)

        themeProp()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        themeProp()
    }

    func themeProp() {
        setTitleColor(colorWhite, for:.normal)
    }

    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()

        themeProp()
    }
}

以我有限的知识,我尝试创建一个函数并尝试在每个类中调用它,但它不起作用。

在每个类声明中重复这 12 行代码没有任何意义。因此,如果有办法避免这种重复,请使用我的代码作为答案。

谢谢!

【问题讨论】:

  • 不需要prepareForInterfaceBuilder。如果只有在 IB 有一些特殊配置时才需要。你经常不需要那个(init 方法被调用,即使是从 IB 实例化的)。你当然不应该在那里打电话给themeProp。一般override init(frame: CGRect = .zero) { ... }required init?(coder aDecoder: NSCoder) { ... }就足够了……

标签: swift xcode ibdesignable


【解决方案1】:

一种可能的解决方案是为这些视图创建一个公共超类。唯一的缺点是您必须为每种类型创建一个超类(UIViews、UIButtons 等)

class DesignableView: UIView {
    override init(frame: CGRect) {  
        super.init(frame: frame)  
        themeProp()  
    }  

    required init?(coder aDecoder: NSCoder) {  
        super.init(coder: aDecoder)  
        themeProp()  
    }  

    override func prepareForInterfaceBuilder() {  
        super.prepareForInterfaceBuilder()  
        themeProp()  
    }

    func themeProp() { }
}

之后,使您的可设计类成为DesignableView 的子类。您只需要在其中覆盖themeProp()

【讨论】:

  • 我们不能创建一个UIControl 的超类来使其对UIViewUIButton 等所有视图都通用吗?
  • @Hemang 你可以,但你很快就会发现自己不断地将视图转换为另一种类型,因为它将是 UIView 而不是 UIButton
  • 你是对的,在这种情况下,如果符合应用程序的长期发展的要求和价值,最好有单独的类。
  • 谢谢!塔马斯·森格尔。我试过你的答案,效果很好。
猜你喜欢
  • 2018-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多