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

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

Any clue?

最佳答案

只需使用image 属性

var isChecked: Bool = false {
    didSet{
        if isChecked == true {
            self.image = checkedImage
        }else{
            self.image = unCheckedImage
        }
    }
}

关于Swift - 如何在自定义类中设置 UIBarButtonItem 的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38382218/

相关文章:

swift - 在 Swift 中编写多个嵌套的 for...in 循环

ios - UITableView:仅在编辑模式下显示选定的单元格背景

ios - 无法更改 UIBarButtonItem 的背景

ios - 如何始终在 pageviewcontroller 中显示键盘

ios - UIImageView 不恢复到原始框架

swift GCDAsyncSocket acceptOnPort :Error: not opening a port?

iphone - 如何在 UIActionSheet 中编写绿色按钮?

iphone - 如何准确检查表面平整度

以编程方式创建的 Swift UIBarButtonItem 位置

objective-c - 子类化 UIBarButtonItem