是否有可能改变UIButton的行动?

时间:2012-01-09 06:13:26

标签: objective-c ios xcode uibutton action

我正在尝试在ios应用程序中更改UIButton的操作。我做了以下代码

 button = [UIButton buttonWithType:UIButtonTypeRoundedRect];

    [button addTarget:self  action:@selector(aMethodShow:) forControlEvents:UIControlEventTouchDown];

    [button setTitle:@"Show View" forState:UIControlStateNormal];

    button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);

    [view addSubview:button];

特别是我想改变这个按钮的动作。所以我做了这个

[button addTarget:self  action:@selector(aMethodHide:) forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Hide View" forState:UIControlStateNormal];

不幸的是这段代码注意工作?

4 个答案:

答案 0 :(得分:17)

我建议在添加新目标之前,首先在removeTarget对象上调用UIbutton,然后使用其他操作添加新目标。

答案 1 :(得分:9)

我认为它会对你有所帮助

[yourButton removeTarget:nil 
               action:NULL 
     forControlEvents:UIControlEventAllEvents]; 

[yourButton addTarget:self 
               action:@selector(yourAction:)
     forControlEvents:UIControlEventTouchUpInside];

答案 2 :(得分:2)

您可以使用相同的操作目标,而不是使用两个目标。在一个目标中,您必须区分如下

-(void)btnAction
{
        if(target1)
          {
            // code for target 1
          }

        else
         {
          // code for target 2
         }

}

此处target1为BOOL值,该值首先设置为YES。每当您想要执行目标2代码时,请更改其值NO

我希望这会对你有帮助。

答案 3 :(得分:0)

我最近制作了一个应用程序并且我遇到了相同的情况,但我找到了解决问题的另一种方法,所以我决定与可能处于相同情况的人分享我的解决方案。

我将尝试解释我在这个问题的背景下所做的事情:

  • 我在button添加了一个标记,并将其与button需要调用的一个函数(例如aMethodShow:)相关联。

    < / LI>
  • button始终调用相同的函数(例如callSpecificFunc:)。 callSpecificFunc:所做的是根据当前aMethodShow:标记调用函数aMethodHidebutton

  • button需要调用其他功能的特定部分中,我只更改了button的标记。

这样的事情:

NSInteger tagOne = 1000; //tag associated with 'aMethodShow' func
NSInteger tagTwo = 1001; //tag associated with 'aMethodHide' func

button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self  action:@selector(callSpecificFunc:) forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[view addSubview:button];

...
// in some part of code, if we want to call 'aMethodShow' function,
// we set the button's tag like this
button.tag = tagOne

...

//Now, if we want to call 'aMethodHide', just change the button's tag
button.tag = tagTwo

...

-(void) callSpecificFunc:(UIButton*)sender
{
    NSInteger tagOne = 1000;
    NSInteger tagTwo = 1001;

    if([sender tag] == tagOne){ 
        //do whatever 'aMethodShow' does
    }else {
        //do whatever 'aMethodHide' does
    }
}

当然它可以应用于两个以上的功能:)

相关问题