簡體   English   中英

Swift - 選擇時切換 UIButton 標題

[英]Swift - Toggle UIButton title when selected

我正在尋求實現一個可用作復選框的按鈕,並使用戶能夠以開/關方式(未選中/選中)切換復選框。 目前我已經使用屬性檢查器設置了我的按鈕,包括“標題”為“X”,“文本顏色”為紅色。

加載后,按鈕會出現一個紅色的“X”,一旦點擊它就會變成一個綠色的勾號。

我的問題是...如何使按鈕再次被點擊以恢復到紅色 X (它的原始狀態),每次點擊時繼續循環?

    @IBAction func check2(_ sender: UIButton) {
     sender.setTitle("✓", for: .normal)
    sender.setTitleColor(UIColor.green, for: UIControlState.normal)
}

謝謝

使用變量跟蹤狀態並根據狀態更新外觀:

    class ViewController: UIViewController{
        @IBOutlet weak var button: UIButton!
        var isChecked = true

        @IBAction func check2(_ sender: UIButton) {
            isChecked = !isChecked
            if isChecked {
                sender.setTitle("✓", for: .normal)
                sender.setTitleColor(.green, for: .normal)
            } else {
                sender.setTitle("X", for: .normal)
                sender.setTitleColor(.red, for: .normal)
            }
        }
    }

為 Swift 3 更新

lazy var toggleBT: UIButton = {

    let button = UIButton()
    button.frame = CGRect(x: 40, y: 100, width: 200, height: 40)
    button.backgroundColor = .orange
    button.isSelected = false   // optional(because by default sender.isSelected is false)
    button.setTitle("OFF", for: .normal)
    button.setTitleColor(.white, for: .normal)
    button.titleLabel?.font = .boldSystemFont(ofSize: 14)
    button.addTarget(self, action: #selector(handleToggleBT), for: .touchUpInside)
    return button
}()

func handleToggleBT(sender: UIButton) {

    sender.isSelected = !sender.isSelected

    if sender.isSelected {

        print(sender.isSelected)
        toggleBT.setTitle("ON", for: .normal)
    }

    else {

        print(sender.isSelected)
        toggleBT.setTitle("OFF", for: .normal)
    }
} // don't forget to add this button as a subView for eg. view.addSubview(toggleBT)

在此處輸入圖像描述

swift5的更新代碼

@IBAction func check2(_ sender: UIButton) {
        
        sender.isSelected = !sender.isSelected //By default sender.isSelected is false  

        if sender.isSelected {
            sender.setTitle("✓", for: .normal)
            sender.setTitleColor(UIColor.green, for: .normal)
        } else {
            sender.setTitle("x", for: .normal)
            sender.setTitleColor(UIColor.red, for: .normal)
        }
    }

暫無
暫無

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

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