Reputation: 321
in my app i call a UIView and that UIView is like a settings screen in my app and i have buttons in the UIView and my question is how do i add actions to the buttons iv added to the UIViews subview? thanks,
Upvotes: 1
Views: 1720
Reputation:
Assuming you're writing code in a view controller for your settings UIView, the UIView is properly bound to the view
property of your controller, and you have referenced one of the buttons with a variable button
, here is what you would write:
- (void)viewDidLoad {
[super viewDidLoad];
[button addTarget:self
action:@selector(buttonPressed)
forControlEvents:UIControlEventTouchUpInside];
}
- (void)buttonPressed
{
// do things here in response to the button being pressed
}
Another way to write that method is passing in a pointer to the button which was actually pressed, like so:
- (void)viewDidLoad {
[super viewDidLoad];
[button addTarget:self
action:@selector(buttonPressed:) // note the extra colon here
forControlEvents:UIControlEventTouchUpInside];
}
- (void)buttonPressed:(id)sender
{
UIButton *buttonWhichWasPressed = (UIButton *)sender;
// now you can do things like hide the button, change its text, etc.
}
Rather than calling addTarget:action:forControlEvents:
, though, in Interface Builder (you should be doing this) after defining the buttonPressed
or buttonPressed:
method above, in the .xib
file with the button go to the second tab in the Inspector after clicking on the Button (it should say Button Connections), and click-drag the Touch Up Inside event to File's Owner, and select "buttonPressed" from the list.
Upvotes: 1