How to set target and action for UIBarButtonItem at runtime

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

提交回复
热议问题