Can I pass a block as a @selector with Objective-C?

前端 未结 9 545
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-30 17:04

Is it possible to pass an Objective-C block for the @selector argument in a UIButton? i.e., Is there any way to get the following to work?

9条回答
  •  旧巷少年郎
    2020-11-30 17:59

    Blocks are objects. Pass your block as the target argument, with @selector(invoke) as the action argument, like this:

    id block = [^{NSLog(@"Hello, world");} copy];// Don't forget to -release.
    
    [button addTarget:block
               action:@selector(invoke)
     forControlEvents:UIControlEventTouchUpInside];
    

提交回复
热议问题