Swift:如何向UIImageView类添加新属性?

时间:2017-08-20 08:41:07

标签: swift class properties

我担心我对Swift来说相对较新,但我尽可能地环顾四周,并且无法找到如何完成这项相对简单的任务!

我想添加一个名为" angle"的新属性。到类UIImageView,这样你就可以使用" image.angle"。这是我所拥有的,试图遵循我使用的教程的方法(注意所需的init?部分是由Xcode建议的,我不太确定它的作用):

class selection_image: UIImageView {

    var angle = Double()

    init(angle: Double) {
        self.angle = angle
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

非常感谢您的帮助!!

2 个答案:

答案 0 :(得分:0)

class selection_image: UIImageView {

    var angle = Double()

    // your new Init
  required convenience  init(angle: Double) {
        self.init(frame: CGRect.zero)

        self.angle = angle
    }

    override init(frame: CGRect) {
        super.init(frame: CGRect.zero)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

答案 1 :(得分:0)

使用Swift 4.2

@jasperthedog。您可以使用运行时的AssociatedObjects使用扩展将属性添加到给定的类,如下所示:

在此示例中,我添加了一个可选的viewAlreadyAppeared:布尔?属性设置为UIViewController。因此,我避免创建UIViewController的子类

extension UIViewController {
    private struct CustomProperties {
        static var viewAlreadyAppeared: Bool? = nil
    }
    var viewAlreadyAppeared: Bool? {
        get {
            return objc_getAssociatedObject(self, &CustomProperties.viewAlreadyAppeared) as? Bool
        }
        set {
            if let unwrappedValue  = newValue {
                objc_setAssociatedObject(self, &CustomProperties.viewAlreadyAppeared, unwrappedValue as Bool?, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            }
        }
    }
}