嗨,我有一个UIBarButton Image的自定义类: class CheckBoxBarButton : UIBarButtonItem { // images let checkedImage = UIImage(named: "img_checked")! as UIImage let unCheckedImage = UIImage(named: "img_unchecked")! as UIImage //bool p
class CheckBoxBarButton : UIBarButtonItem { // images let checkedImage = UIImage(named: "img_checked")! as UIImage let unCheckedImage = UIImage(named: "img_unchecked")! as UIImage //bool property var isChecked: Bool = false { didSet{ if isChecked == true { // here I want to set the checked image for my bar button }else{ // here I want to set the unchecked image for my bar button } } } override func awakeFromNib() { // here I want to add a target when the button is touched. // the actual code is returning an error because UIBarButtonImage doesnt not have addtarget self.addTarget(self, action: #selector(CheckBoxBarButton.buttonClicked(_:)), forControlEvents: UIControlEvents.TouchUpInside) self.isChecked = false } }
您可以使用图像创建一个按钮,并将UIBarButtonItem的customView设置为您的按钮:Any clue?
let button = UIButton() button.setImage(checkedImage )// or button.setImage(unCheckedImage) based on the conditions button.frame = CGRectMake(0, 0, 30, 30) self.customView = button
或者,如果已经定义了按钮,则设置customView图像:
self.customView.setImage(checkedImage )