MeV
MeV

Reputation: 3968

Show/Hide UIButton in another controller

I have a button in my ViewController.swift:

@IBOutlet weak var exampleButton: UIButton!

I would like to show/hide that button from the AppDelegate, when something specific happens (i.e. the app enter background etc.). How can i do that?

Upvotes: 0

Views: 523

Answers (3)

zuziaka
zuziaka

Reputation: 575

Notification is a great idea, but what if your ViewController is not your initial ViewController, or hasn't been initialized yet? It will not be able to catch this notification. Possible solution (maybe not elegant) in extension to other answers is to provide a flag. Your ViewController will be checking it, e.g. in viewDidLoad(). Your flag could be stored in a singleton object which will be catching notification from AppDelegate.

To sum up, you should add notification observer in your ViewController, to catch event from AppDelegate. (like in other answers)

Create singleton class to store appropriate information. Check condition in viewDidLoad:

if YOUR_SINGLETON.YOUR_FLAG == true {
     showButton()
} else {
     hideButton()
}

Don't forget to add notification observer also in your singleton class.

Upvotes: 1

David Hoerl
David Hoerl

Reputation: 41662

Rather than let another object directly manipulate it, use a notification to indicate a state change. The state dictates whether the button appears or not.

Make sure in your notification listener that you only touch the button on the main thread.

Upvotes: 1

Piyush Sharma
Piyush Sharma

Reputation: 1891

One Approach can be - You can use Notifications for this

Add Observer in your view controller where button needs to be hidden

NSNotificationCenter.defaultCenter().addObserver(
    self,
    selector: "hideButton",
    name: @"HIDE_BUTTON_NOTIFICATION",
    object: nil)



func hideButton() -> Void {
  // Hide your button here
  // Remember to hide on main thread
}

From wherever you want to hide the button (like from AppDelegate), you can post this notification

 NSNotificationCenter.defaultCenter().postNotificationName(@"HIDE_BUTTON_NOTIFICATION", object: nil)

Upvotes: 11

Related Questions