【问题标题】:Swift - How to set the image of a UIBarButtonItem in a custom classSwift - 如何在自定义类中设置 UIBarButtonItem 的图像
【发布时间】:2016-07-14 18:59:53
【问题描述】:

您好,我有一个 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
    }
}

有什么线索吗?

【问题讨论】:

  • 为什么不在 didSet 中做任何你需要的事情?

标签: swift cocoa-touch uibarbuttonitem


【解决方案1】:

只需使用image 属性

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

【讨论】:

    【解决方案2】:

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

    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 )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-29
      相关资源
      最近更新 更多