Home > Mobile >  How to connect multiple action to one button Xcode?
How to connect multiple action to one button Xcode?

Time:04-18

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

}

CodePudding user response:

This may be more convenient.

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

CodePudding user response:

Just use a boolean flag which toggles every time the action is fired

private var clearAction = false

@IBAction func actreverse(_ sender: UIButton!) {
   if clearAction {
      // do clear stuff
      clearAction = false
   } else {
      // do reversing stuff
      clearAction = true
   }
}
  • Related