Search code examples
swiftbuttondeselect

deselectd other button when one button isSeleted


I have three button link together called tipChanged . one button was seleted by default (10%) I want to write some code to make one button isSeleted ,the other two will automatically deseleted .my code work but too wordy ,any easy way ? below is my code ,thanks in advance.

import UIKit

class CalculatorViewController: UIViewController {

@IBOutlet weak var zeroPctButton: UIButton!
@IBOutlet weak var tenPctButton: UIButton!
@IBOutlet weak var twentyPctButton: UIButton!

@IBAction func tipChanged(_ sender: UIButton) {
    let pctChoosed = sender.currentTitle
    if pctChoosed == "0%"{
        zeroPctButton.isSelected = true
        tenPctButton.isSelected = false
        twentyPctButton.isSelected = false
    }else if pctChoosed == "10%"{
        zeroPctButton.isSelected = false
        tenPctButton.isSelected = true
        twentyPctButton.isSelected = false
    }else{
        zeroPctButton.isSelected = false
        tenPctButton.isSelected = false
        twentyPctButton.isSelected = true
    }
 }   

}


Solution

  • Remove the if statement and just set them all to false. Then just under where they are set to false set sender.isSelected = true and you should get the desired results.