How to set target and action for UIBarButtonItem at runtime

后端 未结 11 2009
小蘑菇
小蘑菇 2020-12-15 02:44

Tried this but only works for UIButton:

[btn setTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
11条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-15 03:01

    @wp42 It does work today.

    A nifty way of doing this in objective-C is adding a category to UIBarButtonItem class:

    .h file

    #import 
    
    @interface UIBarButtonItem (addons)
    
    -(void)addTarget:(id)target andAction:(SEL)action;
    
    @end
    

    .m file

    #import "UIBarButtonItem+addons.h"
    
    @implementation UIBarButtonItem (addons)
    
    -(void)addTarget:(id)target andAction:(SEL)action{
       [self setTarget:target];
       [self setAction:action];
    }
    
    @end
    

    In practice:

    [myBtn addTarget:self andAction:@selector(myFunction:)];
    

提交回复
热议问题