设置全局UIButton的选择器

时间:2014-02-20 07:17:54

标签: ios objective-c uibutton

我想从全局类中返回全局UIButton

+(UIBarButtonItem *) globalButton {
    UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
    myButton.frame = CGRectMake(0.0, 0.0, 40, 40);
    [myButton addTarget:self action:@selector(???)
                   forControlEvents:UIControlEventTouchUpInside];
    return myButton;
}

因此,如果我从[Global globalButton]拨打viewController,我就可以获得此按钮。我遇到的问题是如何设置选择器,如果我从我的视图控制器调用?

4 个答案:

答案 0 :(得分:0)

在你的控制器中试试这个:

UIBarButtonItem* button = [UIBarButtonItem globalButton];
    [button addTarget:self action:@selector(yourDidTapAction:) forControlEvents:UIControlEventTouchUpInside];

或者在globalButton中:

+(UIBarButtonItem*)globalButtonWithTarget:(id)target andAction:(SEL)action
{
    // ...
    [myButton addTarget:target action:action
                   forControlEvents:UIControlEventTouchUpInside];
    // ...
}

答案 1 :(得分:0)

您应该按照以下方式更改代码,假设您将从UIViewController调用它

+(UIButton *) globalButton:(UIViewController*)delegate {
    UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
    myButton.frame = CGRectMake(0.0, 0.0, 40, 40);
    if([delegate respondsToSelector:@selector(gloBalButtonTapped:)])
        [myButton addTarget:delegate action:@selector(gloBalButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
    return myButton;
}


//Below method should be present in your view controller than only it will be added to myButton click event.
-(IBAction)gloBalButtonTapped:(id)sender{
}

只有在创建UIButton时才会返回UIButton,如果您需要返回UIBarButtonItem而不是创建UIBarButtonItem或者Xcode会发出警告,则只需提示虽然。

答案 2 :(得分:0)

不要在全局类中添加目标,只要您想使用它,就这样使用它。

UIBarButtonItem *btn = [Global globalButton];
btn addTarget:self action:@selector(yourSelector)
                   forControlEvents:UIControlEventTouchUpInside];

或者您可以在 GlobalClass 中将 globalButton 设为属性,并在 setGlobalButton 中编写此方法,然后您可以将其用作任何属性的viewController。

或者,如果您只想在全局中控制它,那么您只能提及此类中提到的选择器。在那种方法中,你可以控制行为。

答案 3 :(得分:0)

我发现最简单的方法是:

+(UIBarButtonItem *) buttonWithSelector:(SEL)selector andSender:(id)sender {
   UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
   myButton.frame = CGRectMake(-40.0, 10.0, 40, 40);
   [myButton addTarget:sender action:selector forControlEvents:UIControlEventTouchUpInside];

   return myButton;
}