How to send a value to the function when clicking on the ui button
NSString *name = @"John";
I need to pass the above variable value, when clicking on the uibutton. Currently I created the uibutton like below:
sendButton = [[UIButton alloc] initWithFrame:CGRectMake(170, 350, 90, 30)];
[sendButton setTitle:@"YES!" forState:UIControlStateNormal];
[sendButton addTarget:self action:@selector(sendAlert forControlEvents:UIControlEventTouchUpInside];
[sendButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
sendB开发者_如何学运维utton.backgroundColor = [UIColor whiteColor];
[popoverView addSubview:sendButton];
[sendButton release];
When I click the above button, it calls the method but I want to pass the variable (name) to the function...
Please guide me to get it ....
Sherry's answer it technically correct but, Im not sure if its a solution for an underlying design pattern issue.
Your variable 'name' will it ever change? and if so how is it changed (field, list selection..etc)?
If it dosnt change then you should #define
it, if it does change (User input) then your event should be looking at the data source, UI Field or an instance Variable.
Though you could subclass UIButton and add properties to it, etc, etc, it will be better for you to make name an instance variable in the popoverView class. The sendAlert method will then be able to access it as well. You don't want to subclass controls every time you need to pass data to them.
You do not need to subclass UIButton.
add an NSString property to popoverView's class (you are following MVC right? popoverView should be a controller). Then before adding it to the subview assign the NSString in your first object to the NSString in your popoverView. done!
you might also consider using notifications if you are going to use that name in other places in your application.
If it is not clear for you post your entire code and I will fix the code for you :)
you can create a custom button as subclass of UIButton You can create properties for that
for example
in .h file
@interface CustomButton : UIButton
{
NSString *name;
}
@property (nonatomic,retain) NSString *name;
@end
.m file
@implementation CustomButton
@synthesize name;
- (void)dealloc{
[name release];
[super dealloc];
}
@end
Now the code where you are creating button
sendButton = [[CustomButton alloc] initWithFrame:CGRectMake(170, 350, 90, 30)];
[sendButton setTitle:@"YES!" forState:UIControlStateNormal];
[sendButton setName:@"John"];
[sendButton addTarget:self action:@selector(sendAlert forControlEvents:UIControlEventTouchUpInside];
[sendButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
sendButton.backgroundColor = [UIColor whiteColor];
[popoverView addSubview:sendButton];
[sendButton release];
now in the method which gets triggered you can access it using that button's property called name
精彩评论