xcode - 使用UIButton事件回调

时间:2015-05-14 16:54:40

标签: xcode events callback uibutton

我有一个错误说“EXEC_BAD_ACCESS”。我想在点击UIButton后运行一个回调。

这是我的代码:

Dialog.m

     - (void)showDialogInParentView: (UIView *)parentView
                          withText:(NSString *)text
                       leftBtnText:(NSString *)t1
                      rightBtnText:(NSString *)t2
                           handler:(void(^)(int))handler {

        vHandler = [handler copy];

        // INIT A CONTROL BUTTON WITH SELECTOR(EVENT) //
        _rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _rightBtn.frame = CGRectMake((self.altView.frame.size.width / 2), 1.0, (self.altView.frame.size.width / 2), self.altView.frame.size.height);
        _rightBtn.titleLabel.textColor = [UIColor whiteColor];
        [_rightBtn setTitle:@"Bla Bla" forState:UIControlStateNormal];

        [_rightBtn addTarget:self action:@selector(button_Click:) forControlEvents:UIControlEventTouchUpInside];

        // DO SOMETHINGS HERE //

}

- (void)button_Click: (UIButton *)sender {
    // CALLBACK HERE  WHEN CLICK THE BUTTON //
    vHandler(1);
}

这是我的代码:

Foo.m

-(void)showDialog {
    Dialog *d = [[Dialog alloc] init];
    [d showDialogInParentView:self.view
                                  withText:@"bla"
                               leftBtnText:@"bla bla"
                              rightBtnText:@"bla bla bla"
                                   handler:^(int res) {
                                       // DO SOMETHINGS //
                                   }];
}

* - (void)showDialogInParentView:(UIView *)parentView中运行vHandler时,代码工作正常                               withText:(NSString *)文本                            leftBtnText:(NSString *)t1                           rightBtnText:(NSString )t2                                handler:(void(^)(int))handle 方法。但是我想在点击UIButton时运行vHandler。

1 个答案:

答案 0 :(得分:0)

我自己解决了这个问题。问题是' vHandler' init对话框类后始终为null。所以我使用了静态变量然后就解决了。

<强> Dialog.h

+ (void)showDialogInParentView: (UIView *)parentView withText:(NSString *)text
                   leftBtnText:(NSString *)t1
                  rightBtnText:(NSString *)t2
                       handler:(void(^)(int))handler;

<强> Foo.m

  static vHandler _handler;