UI按钮和操作问题
我想动态创建一些 UIbutton。并显示标签号。所以我成功地制作了按钮,我单击第一个按钮,它显示标签“null”,然后我单击第二个按钮,然后程序崩溃了。我不确定我的代码的哪一部分出了问题。
这是我的代码:
NSMutableArray *buttonsArray = [[NSMutableArray alloc] initWithObjects:nil];
for(int i = 0; i < [someArray count]; i++)
{
button = [[UIButton alloc] initWithFrame:CGRectMake(btnX,btnY,btnW,btnH)];
button.tag = i;
[buttonsArray addObject:button];
[[buttonsArray objectAtIndex:i] addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
button.titleLabel.text = [NSString stringWithFormat:@"Click it"];
[self.view addSubview:button];
btnY = btnY + 120;
}
-(IBAction) buttonPressed:(id)sender
{
UIButton *btn = (UIButton *)sender;
NSLog(@"%@", btn.tag);
}
I want to create some UIbutton dynamically. And display the tag number. So I successfully made the buttons, I clicked the first button and it shown "null" for the tag, then I click the second button then the program crashed. I am not sure which part of my code went wrong.
Here is my code:
NSMutableArray *buttonsArray = [[NSMutableArray alloc] initWithObjects:nil];
for(int i = 0; i < [someArray count]; i++)
{
button = [[UIButton alloc] initWithFrame:CGRectMake(btnX,btnY,btnW,btnH)];
button.tag = i;
[buttonsArray addObject:button];
[[buttonsArray objectAtIndex:i] addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
button.titleLabel.text = [NSString stringWithFormat:@"Click it"];
[self.view addSubview:button];
btnY = btnY + 120;
}
-(IBAction) buttonPressed:(id)sender
{
UIButton *btn = (UIButton *)sender;
NSLog(@"%@", btn.tag);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
那是因为
tag
是一个NSInteger
并且您必须使用
%ld
作为格式说明符。做That's because
tag
is anNSInteger
and you're doingYou must use
%ld
as the format specifier. Do将代码更改为
NSLog(@"%@",self.but.tag);
或者
NSLog(@"%@",self.but.tag.me)
Change the code as
NSLog(@"%@",self.but.tag);
or
NSLog(@"%@",self.but.tag.me)