Swift - 如何在自定义类中设置UIBarButtonItem的图像

时间:2016-07-14 18:59:54

标签: swift cocoa-touch uibarbuttonitem

您好我有一个UIBarButtonImage的自定义类:

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
    }
}
  

有任何线索吗?

2 个答案:

答案 0 :(得分:2)

只需使用Collection属性

即可
image

答案 1 :(得分:0)

您可以使用图片创建一个按钮,并将customView UIBarButtonItem设置为您的按钮:

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 )