如何以编程方式为按钮设置标签?
我后来想要与标签进行比较得出结论
我试过这个
-(IBAction)buttonPressed:(id)sender{
NSLog(@"%d", [sender tag]);
}
Run Code Online (Sandbox Code Playgroud)
但那只是崩溃的应用.... :(
还有其他想法吗?
干杯伙计
山姆
小智 13
您需要将发件人转换为UIButton:
-(IBAction)buttonPressed:(id)sender{
UIButton *button = (UIButton *)sender;
NSLog(@"%d", [button tag]);
}
Run Code Online (Sandbox Code Playgroud)
编辑:关于消息"无法识别的选择器"...
根据您的错误消息,它无法首先调用buttonPressed方法.请注意,在错误消息中,它正在查找"buttonPressed"(结尾没有冒号),但该方法名为"buttonPressed:".如果您在代码中设置按钮目标,请确保选择器设置为buttonPressed:而不仅仅是buttonPressed.如果您在IB中设置目标,则xib可能与代码不同步.
此外,您的原始代码"[sender tag]"也应该有效但访问特定于按钮的属性,您仍然需要将其强制转换为UIButton.
我知道这是一个老问题,并且在其他问题上已经多次回答,但它在谷歌搜索中排在第二位.所以,这里是为什么崩溃的答案.将其更改为"button.tag"
-(void)myMethod
{
UIButton *theButton = [UIButton buttonWithType:UIButtonTypeCustom];
[theButton addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchDown];
theButton.tag = i;//or whatever value you want. In my case it was in a forloop
}
-(void)buttonPressed:(id)sender
{
UIButton *button = (UIButton *)sender;
NSLog(@"%d", button.tag);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
26921 次 |
| 最近记录: |