Ruben Ruben - 6 months ago 41
iOS Question

Swift set value to enum in my custom class

I'm wondering how can I set a value to my enum that is declared in my Alert.swift custom class in order to the button change the style.
Here is my code so far:

var alert: Alert!


in my viewDidLoad I create the alert

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


and I have a custom class Alert.swift where I have declared the enum:

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


and then in the initializer:

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)
...


My question is, once the alert is created with

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


if I want to change the button style, let's say doing something like that:

alert.buttonType = .Dos


I don't know how to manage that in my Alert.swift class, I only know how to set the style while I'm setting that value while creating the alert.
Thanks in advance!!

Answer

Add something like this to your Alert class:

class Alert {

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


    private func configureForButtonType() {

        switch buttonType {
        case .Uno:
            ...
            break

        case .Cero:
            ...
            break

        case .Dos:
            ...
            break

        case .Tres:
            ...
            break
        }
    }
}

Put all of your styling from the switch on buttonType in the configureForButtonType() method. When buttonType is set at initialization, the class will configure itself.