fossdeep fossdeep - 2 months ago 6
iOS Question

If a button is created inside a function, where is the right place to add it, so it is accessible?

func createButton() {
let b = UIButton()
// Some code to modify image of button
b.addTarget(self, action: "fade", forControlEvents: .TouchDown)
self.view.addSubview(b)
// Some code to add constraints
}

func fade() {
UIView.animeWithDuration(5, animations: {
self.b.alpha = 0 // Error (ViewController has no member 'b')
}


Do I get this error because,
createButton()
has a separate view from
ViewController
? Because I have tried passing in the button, and using
sender.view.b.alpha = 0
, but
UIButton
has no
view
.

Thank you.

Answer

You need to declare the button in the right scope. Currently you´re only declaring it in the function scope of createButton. But you could make it an instance variable of your class. Then you can access it from both methods.

class XYZ
{

     var button: UIButton?

     func createButton() {
        self.button = UIButton()
        // Some code to modify image of button
        self.button.addTarget(self, action: "fade", forControlEvents: .TouchDown)
        self.view.addSubview(self.button)
        // Some code to add constraints    
     }

     func fade() {
          UIView.animeWithDuration(5, animations: {
                self.button.alpha = 0
     }
}

Also here is an article about scopes and lifetime of objects in Swift.

Hope this helps.

Comments