如何在按下UIButton时打印此变量的值?
问题描述:
// My Button code
UIButton *ticketButtonObj=[[ticketButton alloc]initWithFrame:CGRectMake(0.0f, 115.0f, 500.0f, 40.0f) ;
int col=10;
[ticketButtonObj addTarget:self action:@selector(ShowNumber:) forControlEvents:UIControlEventTouchUpInside];
[self.window addSubview:ticketButtonObj];
// ...
- (void) ShowNumber:(id)sender{
// here i want to get the Value of Col
}
在上面的代码中,当我按下按钮时,我想打印col变量的值在ShowNumber
方法中。我怎样才能做到这一点?如何在按下UIButton时打印此变量的值?
答
Col是一个局部变量,在方法返回后会被销毁。
您需要为您创建一个实例变量才能够访问该值。
答
不要使用正常的局部变量,我建议不要使用int。使用一个NSInteger
并将其设置为一个属性:
@interface YourClassName : UIViewController
{
NSInteger col;
}
@property (nonatomic) NSInteger col;
然后@synthesize
变量col
以及任何你在代码中喜欢使用它。
答
您可以:
UIButton *ticketButtonObj=[[ticketButton alloc]initWithFrame:CGRectMake(0.0f, 115.0f, 500.0f, 40.0f) ;
int col=10;
ticketButtonObj.tag = col;
[ticketButtonObj addTarget:self action:@selector(ShowNumber:) forControlEvents:UIControlEventTouchUpInside];
[self.window addSubview:ticketButtonObj];
// ...
- (void) ShowNumber:(id)sender{
NSLog(@"%@", [(UIButton*) sender tag]);}