如何连接多个动作到一个按钮Xcode?



我是ios开发的新手,我有一个简单的问题,我仍然无法解决。事情是我做一个反向文字应用程序,当用户第一次点击按钮,它会反转样本文本,但当用户第二次点击相同的按钮,它会清除样本文本和结果标签内的文本。因此,主要问题是如何将"明确行动"与"明确行动"联系起来。到同一个按钮?

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

这样可能更方便。

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

只需使用布尔标志,每次触发动作时都会切换

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

相关内容

  • 没有找到相关文章

最新更新