iosswiftxcodemobileibaction

How to connect multiple action to one button Xcode?


I'm a noob in ios development and i have a simple problem which i still cannot solve. The thing is i making a reverse words app and when the user tap the button at first time it will reverse the sample text but then when user tup second time same button it will clear the text inside sample text and result label. So the main question is how to connect the "clear action" to the same button ?

@IBOutlet var actReverseStyle: UIButton!

@IBOutlet weak var sampletext: UITextField!
var sample: String {return sampletext.text ?? ""
    }

@IBOutlet weak var resultscreen: UILabel!

@IBAction func actreverse(_ sender: UIButton!) {
    let sampleSentence = sample
            
        func reverseWolrdsInSentance(sentanse:String) -> String{
            let allWords = sampleSentence.components(separatedBy: " ")
            var newSentence = ""
            for word in allWords{
             if newSentence != ""{
                 newSentence += " " }
            let reverseWord = String(word.reversed())
            newSentence += reverseWord}
            
            return newSentence}
            resultscreen.text = reverseWolrdsInSentance(sentanse: sampleSentence)
    
            actReverseStyle.setTitle("Clear", for: .normal)
        }
        

}

Solution

  • This may be more convenient.

    @IBAction func actreverse(_ sender: UIButton!) {
        sender.isSelected.toggle();
        if sender.isSelected {
            // do reverse
        } else {
            // do clear
        }
    }