The*_*Man 0 iphone methods cocoa-touch objective-c
我的故事板上有一个巨大的疯狂场景,有36个不同的按钮,每个按钮在点击时都意味着不同的东西.我真的不想创建36种不同的方法,所以如何在按下36个按钮之一时调用的方法中引用按钮标题或按钮名称.
这可能是一个简单的问题,但我是iOS和Objective C的新手......
谢谢!
您可以创建一个方法,如下所示:
- (IBAction)buttonTapped:(id)sender{
// The button that was tapped is called "sender"
// This will log out the title of the button
//NSLog(@"Button: %@", sender.titleLabel.text);
//Edit: You need a cast in the above line of code:
NSLog(@"Button: %@", ((UIButton *)sender).titleLabel.text);
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用Interface Builder连接到所有按钮.你可以使用某种if/else逻辑来测试点击了哪个按钮.
您可以检查titleLabel属性,也可以IBOutlet为每个按钮分配一个并检查它.
例如:
if([sender isEqual:buttonOutlet1]){
//If this button is attached to buttonOutlet1
//do something
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以简单地使用每个按钮的标签,而不必担心插座.
第三种选择是在代码中生成和布局按钮,然后将它们作为按钮数组的元素进行访问.
第四个选项是向按钮添加标签并检查功能中按钮的标签.