How to set target and action for UIBarButtonItem at runtime

后端 未结 11 1963
小蘑菇
小蘑菇 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:46

    Set target and action of your UIBarButtonItem

    Swift 5 & 4

    button.target = self
    button.action = #selector(action)
    
    @objc func action (sender:UIButton) {
        print("action")
    }
    
    0 讨论(0)
  • 2020-12-15 02:52

    You may want to try out the addTarget method.

    0 讨论(0)
  • 2020-12-15 02:53

    I ran into a similar problem... I assume you mean that if your UIButton is not part of your UITabBar to call btnClicked then it works appropriately. If this is the problem you are proposing then, check your btnClicked method and change it from:

    -btnClicked:(id)sender
    

    to

    -(void) btnClicked:(id)sender
    

    that, and declare btnClicked in the header file...

    For what it's worth, this is how I setup a button in tabbarbuttonitem:

    UIBarButtonItem *exampleButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"button.png"] style:UIBarButtonItemStylePlain target:self action:@selector(btnClicked:)];
    
    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
  • 2020-12-15 02:56

    Just set the UIBarButtonItem's target and action properties directly.

    0 讨论(0)
  • 2020-12-15 02:59

    For custom views: use an UITapGestureRecognizer and set up isUserInteractionEnabled to true.

        profileImageView.isUserInteractionEnabled = true
    
        let tap = UITapGestureRecognizer(target: self, action: #selector(handleProfileImageTap))
        profileImageView.addGestureRecognizer(tap)
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: profileImageView)
    
    0 讨论(0)
提交回复
热议问题