How to use UIButton as Toggle Button?

前端 未结 5 2281
庸人自扰
庸人自扰 2020-12-15 05:03

I am trying to create a toggle button for each cell in my table. When pressed, it will change the image and when pressed again it will change the image again -- Toggle.

5条回答
  •  独厮守ぢ
    2020-12-15 05:32

    Swift 4.0 Solution (using Storyboards)

    First, ensure the UIButton Type is set to Custom in the Attributes Inspector.

    // Reference to UIButton in Storyboard
    @IBOutlet weak var toggleButton: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        // assumes you have two images in the bundle/project 
        // called normal.png and selected.png.
        let normalImage = UIImage(named: "normal.png")
        let selectedImage = UIImage(named: "selected.png")
    
        toggleButton.setImage(normalImage, for: .normal)
        toggleButton.setImage(selectedImage, for: .selected)
    }
    

    Below screenshot demonstrates reference to toggleButton in Storyboard, and Touch Up Inside Event, ie: a user tapping the button, which fires off didPressButton below.

    @IBAction func didPressButton(_ sender: Any) {
    
        // if the button was selected, then deselect it.
        // otherwise if it was not selected, then select it.
        toggleButton.isSelected = !trackingButton.isSelected
    
        if toggleButton.isSelected {
            print("I am selected.")
    
        } else {
            print("I am not selected.")
        }
    }
    

提交回复
热议问题