繁体   English   中英

快捷一键3条信息

[英]Swift one button 3 messages

我是Swift的新手,正在Xcode上进行编码。 我正在尝试做一个“你好,世界!” 在Swift中使用一个只有一个屏幕,一个按钮和一个显示标签的应用。

我的目标是通过单击按钮来显示三种不同的消息。 为了明确起见,每次单击按钮时,都会循环显示消息。

我尝试用switch解决它,这是我的(未完成的尝试)

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var textBox: UILabel!

    var userTapped = false

    @IBAction func tappedMe(_ sender: UIButton) {
        let me =
        if userTapped {
            switch me {
            case me : textBox.text = "Hello, World!"
            case me : textBox.text = "Hello, Human!"
            case me : textBox.text = "OK scram."
            default : break
            }
        userTapped = true
        }
    }
}

我不确定我能使me等于什么,或者我的解决方案是否很好。

如果我正确理解,您可以执行以下操作以实现您的目标:

import UIKit

class ViewController: UIViewController {
@IBOutlet weak var textBox: UILabel!

// Integer to track number of times button has been tapped
var tapCount = 0

// Max total of text variations, for this case 2 (you have three different values, but always start with zero)
let max = 2 

@IBAction func tappedMe(_ sender: UIButton) {
    // Try different conditions for value of tapCount
    switch tapCount {
        case 0: 
            textBox.text = "Hello, World!"
        case 1: 
            textBox.text = "Hello, Human!"
        case 2: 
            textBox.text = "OK scram."
        default : break
    }

    // If this is the max number of times you want to display changing text, reset tapCount to zero, otherwise increment tapCount.
    if tapCount < max {
        tapCount += 1
    } else {
        tapCount = 0
    }
} 


}
class ViewController: UIViewController {

    @IBOutlet weak var textBox: UILabel!

    let strings = ["Hello, World!", "Hello, Human!", "OK scram."]
    var tapCount = 0

    @IBAction func tappedMe(_ sender: UIButton) {
        textBox.text = strings[tapCount]
        tapCount = (tapCount + 1) % strings.count
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM