Dave
Dave

Reputation: 12216

Remove Programmatically Added UIButton

In my view controller's viewDidLoad, I added a button:

        let tutorialButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton
        tutorialButton.frame = CGRectMake(0, (UIScreen.mainScreen().bounds.size.height/4)*3, UIScreen.mainScreen().bounds.size.width, 20)
        tutorialButton.titleLabel?.textAlignment = NSTextAlignment.Center
        tutorialButton.backgroundColor = UIColor.clearColor()
        tutorialButton.setTitle("View Quick Tutorial", forState: UIControlState.Normal)
        tutorialButton.addTarget(self, action: "giveTutorial:", forControlEvents: UIControlEvents.TouchUpInside)

        self.view.addSubview(tutorialButton)

The button appears where I want it and that part works great. But after it has served it's purpose and I no longer want it visible, how do I remove the button from the view? I've researched that it's usually done like this:

buttonName.removeFromSuperview

However, when I type in buttonName, it does not recognize the button. I guess because there's no IBOutlet. So then what code can I stick in a method that'll get this button removed?

Upvotes: 2

Views: 4712

Answers (2)

Dave
Dave

Reputation: 12216

My problem turned out to be not in what code I typed, but where I typed it. Because I wanted the view to be added upon load, I added the whole chunk of code to my viewDidLoad. However, this line did not belong there:

let tutorialButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton

By declaring tutorialButton within the viewDidLoad, I caused it to not be accessible/reference-able outside of the viewDidLoad. To fix this, all I had to do was move that line outside of the viewDidLoad.

let tutorialButton = UIButton.buttonWithType(UIButtonType.System) as! UIButton

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    ...

This is a key thing to take note of if you plan to edit or remove the view later, from a method other than the viewDidLoad. Now that I made the change, I can add the removeFromSuperview call to a buttonPress and it works great:

tutorialButton?.removeFromSuperview

Upvotes: 2

Mundi
Mundi

Reputation: 80271

Declare a class variable (not an IBOutlet) to hold the button reference.

var tutorialButton : UIButton?

Populate button in code and remove with

tutorialButton?.removeFromSuperview

Upvotes: 6

Related Questions