skip to Main Content

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

}

2

Answers


  1. 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
       }
    }
    
    Login or Signup to reply.
  2. This may be more convenient.

    @IBAction func actreverse(_ sender: UIButton!) {
        sender.isSelected.toggle();
        if sender.isSelected {
            // do reverse
        } else {
            // do clear
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search