Swift将值设置为我的自定义类

时间:2016-05-27 19:44:02

标签: ios swift enums

我想知道如何设置我的 Alert.swift 自定义类中声明的枚举值,以便按钮更改样式。 到目前为止,这是我的代码:

var alert: Alert!

在我的viewDidLoad中我创建了警告

alert = Alert(frame: CGRect(x: 0, y: 0, width: self.view.frame.width , height: 60), buttonType: .Uno, disabled: true)

我有一个自定义类Alert.swift,我已经声明了枚举:

enum ButtonType {
    case Cero
    case Uno
    case Dos
    case Tres
}

然后在初始化程序中:

convenience init(frame: CGRect, buttonType: ButtonType, disabled: Bool = false) {
    self.init(frame: frame)

    switch buttonType {
    case .Uno:
        rightButton = UIButton(type: UIButtonType.System) as UIButton
        rightButton.frame = CGRectMake(self.alertView.frame.width-60, 0, 60, 60)
        rightButton.backgroundColor = UIColor.greenColor()
        rightButton.addTarget(self, action: nil, forControlEvents: UIControlEvents.TouchUpInside)
        rightButton.setImage(UIImage(named: "rightButtonImage"), forState: UIControlState.Normal)
        rightButton.imageView?.contentMode = UIViewContentMode.Center
        alertView.addSubview(rightButton)
        ...

我的问题是,一旦使用

创建警报
alert = Alert(frame: CGRect(x: 0, y: 0, width: self.view.frame.width , height: 60), buttonType: .Uno, disabled: true)

如果我想改变按钮样式,那就说这样做:

alert.buttonType = .Dos

我不知道如何在 Alert.swift 类中管理它,我只知道在创建警报时设置该值时如何设置样式。 在此先感谢!!

3 个答案:

答案 0 :(得分:2)

使用Swift这实际上是一个很容易解决的问题。所以你需要的是一些状态。您需要知道当前按钮设置是什么。我会为此推荐一个类属性,例如:

var buttonState = ButtonType.Uno

好。完成后,您只需检查此属性中的更改即可。你可以在这里做几件事,但最简单的就是使用didSet工具。

var buttonState = ButtonType.Uno {
   didSet {
      switch buttonState {
         case .Uno:
            ...
      }
   }
}

理想情况下,您不希望在此处使用整个开关,但您可以轻松地将其移动到某个功能中并从此处引用它。

希望这会有所帮助:)

答案 1 :(得分:2)

在您的Alert课程中添加以下内容:

class Alert {

    var buttonType: ButtonType {
        didSet {
            configureForButtonType()
        }
    }


    private func configureForButtonType() {

        switch buttonType {
        case .Uno:
            ...
            break

        case .Cero:
            ...
            break

        case .Dos:
            ...
            break

        case .Tres:
            ...
            break
        }
    }
}

switch buttonType中的所有样式放在configureForButtonType()方法中。在初始化时设置buttonType时,类将自行配置。

答案 2 :(得分:1)

向Alert类添加属性:

var buttonType {
    didSet {
        print("Add update here or call func")
    }
}

在初始化代码中设置此属性:

convenience init(frame: CGRect, buttonType: ButtonType, disabled: Bool = false) {
    self.buttonType = buttonType    
    self.init(frame: frame)
    ...
}

现在可以在init之外更改属性,类可以根据需要进行其他更改。