How to set target and action for UIBarButtonItem at runtime

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

Tried this but only works for UIButton:

[btn setTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
11条回答
  •  北荒
    北荒 (楼主)
    2020-12-15 02:55

    UIBarButtonItem doesnt have the same addTarget method so you have to set them directly as follows

    btn.target = self;
    btn.action = @selector(barButtonCustomPressed:);
    

    ...

    // can specify UIBarButtonItem instead of id for this case
    -(IBAction)barButtonCustomPressed:(UIBarButtonItem*)btn 
    {
        NSLog(@"button tapped %@", btn.title);
    }
    

提交回复
热议问题