【问题标题】:Xcode: UIButton setImage does not change the image of the buttonXcode:UIButton setImage 不会改变按钮的图像
【发布时间】:2020-12-21 13:37:48
【问题描述】:

注意:其他人也问过类似的问题,但提供的答案都没有解决我的问题。

这是我的代码:

   @IBOutlet var testButton:UIButton!
    override func viewDidLoad() {
       self.testButton.setImage(UIImage(named: "icn_checkbox_")?.imageWithColor(color: CMStyle.darkBlueColor), for: .normal)
        self.testButton.setImage(UIImage(named: "icn_checked")?.imageWithColor(color: CMStyle.darkBlueColor), for: .selected)
        
    }
 @IBAction func testButtonAction(_ sender: Any) {
        print("INSIDE testButtonAction")
              self.testButton.isSelected = !self.testButton.isSelected
              print("self.testButton.isSelected: ",self.testButton.isSelected)
    }

这是按钮:
.
这些是按钮的特性:
.
这是用于.normal 状态的 icn_checkbox_ 图像:
这是用于.selected 状态的 icn_checked 图像:

testButtonAction 中的代码被执行。所以我真的不明白为什么图像不会改变(为什么按钮没有被选中)。

【问题讨论】:

  • 不,它被记录为可选

标签: ios swift xcode uibutton tvos


【解决方案1】:

您可以在 Storyboard 中设置按钮状态的图像,其中 Default = .normal 和 Selected = .selected

在那里选择并设置图像。如果您使用的是模板图像,则带有颜色的图像类似于 tintColor

【讨论】:

    【解决方案2】:

    你可以用这个:

    @IBOutlet var testButton: UIButton!
    override func viewDidLoad() {
           self.testButton.setImage(UIImage(named: "icn_checkbox_")?.imageWithColor(color: CMStyle.darkBlueColor), for: .normal)
    }
    
    @IBAction func testButtonAction(_ sender: Any) {
           print("INSIDE testButtonAction")
           self.testButton.isSelected = !self.testButton.isSelected
           if self.testButton.isSelected {
              self.testButton.setImage(UIImage(named: "icn_checked")?.imageWithColor(color: CMStyle.darkBlueColor), for: .normal)
           } else {
              self.testButton.setImage(UIImage(named: "icn_checkbox_")?.imageWithColor(color: CMStyle.darkBlueColor), for: .normal)
           }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多