简体   繁体   中英

Setting UIButton target

I am trying to call a method when buttonCancel is pressed in this way:

+ (DejalActivityView *)activityViewForView:(UIView *)addToView withLabel:(NSString *)labelText width:(NSUInteger)aLabelWidth;
{
// Immediately remove any existing activity view:
if (dejalActivityView)
    [self removeView];

// Remember the new view (so this is a singleton):
dejalActivityView = [[self alloc] initForView:addToView withLabel:labelText width:aLabelWidth];

buttonCancel = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[buttonCancel addTarget:self
                 action:@selector(callCancelAlert:)
       forControlEvents:UIControlEventTouchDown];
[buttonCancel setTitle:@"Cancel upload" forState:UIControlStateNormal];
buttonCancel.frame = CGRectMake(250, 560, 300, 40);
[addToView addSubview:buttonCancel];
[buttonCancel setImage:[UIImage imageNamed:@"socialize-navbar-bg.png"] forState:UIControlStateNormal];

return dejalActivityView;
}

and the method

 -(IBAction)callCancelAlert:(id)sender{

UIAlertView *alert = [[UIAlertView alloc]
                      initWithTitle: @"Announcement"
                      message: @"It turns out that you are playing Addicus!"
                      delegate: nil
                      cancelButtonTitle:@"OK"
                      otherButtonTitles:nil];
[alert show];
//[alert release];
}

I am receiving this error:

'NSInvalidArgumentException', reason: '+[DejalBezelActivityView callCancelAlert:]: unrecognized selector sent to class 0x3184e4' * First throw call stack: (0x327862a3 0x3a61f97f 0x32789ca3 0x32788531 0x326dff68 0x346790c5 0x34679077 0x34679055 0x3467890b 0x3467859b 0x345a1523 0x3458e801 0x3458e11b 0x362805a3 0x362801d3 0x3275b173 0x3275b117 0x32759f99 0x326ccebd 0x326ccd49 0x3627f2eb 0x345e2301 0x39445 0x3aa56b20) libc++abi.dylib: terminate called throwing an exception

And the app crashes.

Your first method is a class method (+) not an instance method (-) therefor you're in a Class context.

When you write

[buttonCancel addTarget:self
                 action:@selector(callCancelAlert:)
       forControlEvents:UIControlEventTouchDown];

self point not to a class instance (eg create by and alloc & init messages) but to the class itself.

Since in the same method you alloc an instance of DejalActivityView you should do this:

[buttonCancel addTarget:dejalActivityView
                 action:@selector(callCancelAlert:)
       forControlEvents:UIControlEventTouchDown];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM