【问题标题】:Custom object class in SwiftSwift 中的自定义对象类
【发布时间】:2015-07-01 11:10:05
【问题描述】:

在我的应用中,我需要有很多具有相似属性的标签。假设它们都必须是绿色的。我不想每次都说lbl.color = UIColor.greenColor()。我怎样才能制作一个自定义对象类/结构,让我说类似var myLbl = CustomLbl()CustomLblbeing my class)。

我不确定这是否是您应该这样做的方式。如果没有,我可以通过其他方式进行操作。
另外,在我的应用中,我会有更多属性,但我只选择了这个作为示例。

谢谢!

【问题讨论】:

    标签: xcode swift class custom-object


    【解决方案1】:

    无需子类化,您只需添加一个方法来根据需要配置标签:

    func customize() {
        self.textColor = UIColor.greenColor()
        // ...
    }
    

    还有一个静态函数,它创建一个UILabel 实例,自定义并返回它:

    static func createCustomLabel() -> UILabel {
        let label = UILabel()
        label.customize()
        return label
    }
    

    将它们放入 UILabel 扩展名中就完成了 - 您可以使用以下命令创建自定义标签:

    let customizedLabel = UILabel.createCustomLabel()
    

    或将自定义应用到现有标签:

    let label = UILabel()
    label.customize()
    

    更新:为清楚起见,这两种方法必须放在扩展中:

    extension UILabel {
        func customize() {
            self.textColor = UIColor.greenColor()
            // ...
        }
    
        static func createCustomLabel() -> UILabel {
            let label = UILabel()
            label.customize()
            return label
        }
    }
    

    【讨论】:

    • 我在 label.customize() 的静态函数中收到一条错误消息 UILabel does not have a member named customize... @Antonio
    • 你把它们放在extension UILabel { ... }里面了吗?
    【解决方案2】:

    您应该使用基类来创建自己的标签、按钮等。

    class YourLabel: UILabel {
    
        init(coder aDecoder: NSCoder!) { 
            super.init(coder: aDecoder) 
    
            //you can set your properties    
            //e.g
            self.color = UIColor.colorGreen()
    }
    

    【讨论】:

    • 我稍微修改了代码以消除一些错误。我必须把required放在init(coder aDecoder: NSCoder!) {之前,而且颜色应该是greenColor()(我的错)。如何制作具有这些属性的标签?
    猜你喜欢
    • 1970-01-01
    • 2020-10-29
    • 1970-01-01
    • 2019-07-28
    • 1970-01-01
    • 1970-01-01
    • 2022-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多