繁体   English   中英

快速设置值以在我的自定义类中枚举

[英]Swift set value to enum in my custom class

我想知道如何为我的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类中进行管理,我只知道如何在创建警报时设置样式时设置样式。 提前致谢!!

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

var buttonState = ButtonType.Uno

好的。 现在,您可以简单地检查此属性中的更改。 您可以在此处执行几项操作,但最简单的方法是使用didSet工具。

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

理想情况下,您不希望将整个开关都放在这里,但是可以轻松地将其移入功能并从此处引用它。

希望这可以帮助 :)

在您的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
        }
    }
}

将所有样式都通过configureForButtonType()方法中的buttonType上的switch进行。 在初始化时设置buttonType时,该类将自行配置。

向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之外更改属性,并且该类可以根据需要进行其他更改。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM