Quote:
Originally Posted by yangMaster97
Hey, newbie programmer here. How do I assign a text (or string) to a UIButton on another view? What is the code?
|
In general, one view controller should not be mucking with another view controller's buttons directly. You really want each view controller's internals to be hidden, so that you can change it later without having to tell other objects about the changes. It would be better to add a method ("changeMessage") to the second view controller that tells the view controller to display a different message, and the second view controller then changes the button text itself. That way, if you decide, later, to change the button to a label, all you have to do is change the changeMessage method to display the message to a label. With your way, changing the UI in one view controller requires you to change the code in every other view controller that cares about it.
So, with that in mind, here's what to do.
In "SecondViewController" add a method
Code:
-(void) changeButtonMessage: (NSString*) newMessage
{
myButton.text = newMessage
}
Make sure that method declaration is in the header so other objects can call it.
Add properties to all your view controllers in your app delegate.
When you create your view controllers, set up the properties in your app delegate to point to the view controllers.
#include the header of your app delegate in any view controller that needs to talk to other view controllers. (Let's say your app delegate is of class "MyAppDelegate".)
Now, you can use code like this anywhere in your app:
Code:
MyAppDelegate* theAppDelegate = [UIApplication sharedApplication].delegate;
OtherViewController* theOtherViewController = theAppDelegate.theOtherViewController;
[theOtherViewController changeButtonMessage: @"new button text"];
This approach works, but it isn't the greatest object oriented design. It causes "coupling" between the app controller and the view controllers. I wrote a post that explains a better way to communicate data and messages between objects:
Sharing data between view controllers and other objects