当前位置 : 主页 > 手机开发 > 其它 >

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

来源:互联网 收集:自由互联 发布时间:2021-06-11
嗨,我有一个UIBarButton Image的自定义类: class CheckBoxBarButton : UIBarButtonItem { // images let checkedImage = UIImage(named: "img_checked")! as UIImage let unCheckedImage = UIImage(named: "img_unchecked")! as UIImage //bool p
嗨,我有一个UIBarButton Image的自定义类:

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

Any clue?

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

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 )
网友评论