我的视图中有两个按钮,一个事件必须在每个按钮的selector
之间交换
换言之(不是法典):
button1选择器= button2选择器;
button2选择器= button1选择器;
编辑
事件一直是这样的,但是负责在两个按钮操作之间交换的代码才是我所需要的。
我需要的是:
1-如何删除选择器并将其存储以用于另一个按钮。
2-如何使用保存的选择器作为按钮选择器
PS
在我的代码中,button1和button2根据用户选择从9个选择器中随机选择,然后输入包含我的两个按钮的视图
发布于 2012-10-09 15:37:03
这假设您只有一个与每个按钮的目标相关联的操作(假定为self
)。
NSString *oldAction1String = [[button1 actionsForTarget:self forControlEvent:UIControlEventTouchUpInside] objectAtIndex:0];
NSString *oldAction2String = [[button2 actionsForTarget:self forControlEvent:UIControlEventTouchUpInside] objectAtIndex:0];
SEL oldAction1 = NSSelectorFromString(oldAction1String);
SEL oldAction2 = NSSelectorFromString(oldAction2String);
[button1 removeTarget:self action:oldAction1 forControlEvents:UIControlEventTouchUpInside];
[button1 addTarget:self action:oldAction2 forControlEvents:UIControlEventTouchUpInside];
[button2 removeTarget:self action:oldAction2 forControlEvents:UIControlEventTouchUpInside];
[button2 addTarget:self action:oldAction1 forControlEvents:UIControlEventTouchUpInside];
有很多方法可以绕过这么多重复的代码,但我觉得这种方式更容易读懂。最后,该解决方案真正根据运行时情况交换操作,而不是依赖于在编译时分配特定的操作,这应该满足您的更新要求。希望这能有所帮助!
发布于 2012-10-09 15:06:20
我通常会在某个地方创建一个BOOL,并检查它是否为真,并指导它所需要的代码。
-(IBAction)button1:(id)sender {
if (boolIsTrue) {
// do this
}
}
-(IBAction)button2:(id)sender {
if (!boolIsTrue) {
// do this
}
}
像这样的东西会管用的。
发布于 2012-10-09 15:39:57
考虑对两个按钮使用相同的选择器。
它使您的代码更加优雅和易于维护:没有动态选择器(更少调试),而且所有情况都在同一代码块中。毕竟,您有一个“发件人”(即UIButton本身)。
您可以通过标记来区分这两个按钮(如果通过代码创建按钮可以定义这些按钮),或者通过比较保留的按钮(您的选择)来区分这两个按钮。
-(IBAction)selectorForBothButtons:(id)sender
{
if ((UIButton*)sender.tag == FIRST_BUTTON_TAG ) {
if (!shouldSwapActions) {
do_something;
} else {
do_something_else ;
}
} else { //second button
other_actions..
}
}
https://stackoverflow.com/questions/12802984
复制相似问题