Swift: 一键切换UIView中的多个测试消息

Swift: one button to alternate multiple test message in UIView

我正在尝试实现一个按钮 - 单击一次显示第一条消息,第二次单击将更改为第二条消息,第三次单击将更改为第三条消息。

我查找了一个可能的解决方案是使用 UITapGestureRecognizer - single tap and double tap,这意味着我可以触发按钮(单击显示第一条消息,双击显示第二条消息)。

但是,如果我有多于两行,我只想通过单击每一行来显示它们(如动画)。是否可以只在一个 UIView 和 UIbutton 中处理它?

我目前有 3 条简单的消息:

@IBOutlet weak var Textfield: UITextView!
@IBOutlet weak var Changingbutton: UIButton!

 @IBAction func ChangingTapped(_ btn: UIButton) {
    Textfield.text = "Changing to driving"
    Textfield.text = "Changing to walking"
    Textfield.text = "Changing to cycling"
}

现在的问题是,当我点击按钮时,它只会显示最后一条消息。这可能不是一个聪明的方法。

非常感谢您的意见,如果这是一个相当简单的问题,我很抱歉。

为什么不设置一个计数器并在每次激活 IBAction 时递增它?

var x = 0
@IBAction func ChangingTapped(_ btn: UIButton) {
  if(x==0){
      Textfield.text = "Changing to driving"
  }
  else if(x==1){
       Textfield.text = "Changing to walking"
  }
  else{
     Textfield.text = "Changing to cycling"
  }

   x +=1 

   //if x needs to be reset 
   /*
     if(x > 2) x = 0
   */


}

您可以实现自定义 CaseIterable 枚举来执行循环,这样您每次按下按钮时都可以获得下一个元素:

extension CaseIterable where Self: Equatable {
    var allCases: AllCases { Self.allCases }
    var nextCase: Self {
        let index = allCases.index(after: allCases.firstIndex(of: self)!)
        guard index != allCases.endIndex else { return allCases.first! }
        return allCases[index]
    }
    @discardableResult
    mutating func next() -> Self {
        self = nextCase
        return self
    }
}

使用您的交通方式创建枚举:

enum Mode: String, CaseIterable {
    case cycling, driving, walking
}

向您的视图控制器添加模式属性并设置初始值

var mode: Mode = .cycling

现在每次按下按钮时,您都可以简单地调用下一个模式方法:

func ChangingTapped(_ btn: UIButton) {
    Textfield.text = "Changing to " + mode.next().rawValue
}

注意:Swift 命名约定以小写字母开头的方法和属性命名。