簡體   English   中英

Xcode:UIButton setImage 不會改變按鈕的圖像

[英]Xcode: UIButton setImage does not change the image of the button

注意:其他人也問過類似的問題,但所提供的答案都沒有解決我的問題。

這是我的代碼:

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

這是按鈕:
在此處輸入圖片說明 .
這些是按鈕的特性:
在此處輸入圖片說明 .
這是用於icn_checkbox_圖像.normal狀態:
在此處輸入圖片說明 這是用於.selected狀態的icn_checked圖像: 在此處輸入圖片說明

testButtonAction的代碼被執行。 所以我真的不明白為什么圖像不會改變(為什么按鈕沒有被選中)。

你可以使用這個:

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

您可以僅在 Storyboard 中為按鈕狀態設置圖像,其中 Default = .normal 和 Selected = .selected

在此處輸入圖片說明

選擇選定並在那里設置圖像。 如果您使用的是模板圖像,則帶有顏色的圖像類似於 tintColor

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM