在 While Loop Swift 中更新文本 [英] Update Text in While Loop Swift

查看:19
本文介绍了在 While Loop Swift 中更新文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序有一个 while 循环,它运行一些代码,在执行过程中生成各种文本语句.问题是 UILabel 只打印系列中的最后一行文本(我的理解是因为它迭代太快).如何让标签打印遇到的所有文本,就像在控制台输出中看到的那样?

My program has a while-loop that runs some code, generating various text statements as it goes along. The problem is that the UILabel only prints the last line of text in the series (my understanding is because it iterates too quickly). How do I get the label to print all of the text encountered, like one would see in console output?

我查看了此链接,但该示例似乎与我的情况不符,并且不确定如何实施修复(如果那是正确的):在while循环Swift中更新标签

I looked at this link but the example doesn't seem to match my situation and not sure how to implement the fix (if that's even the right one): Update Label In While Loop Swift

class ViewController: UIViewController {

var locationArray = ["Place A", "Place B", "Place C", "Place D"]
var timeStamp = 0
var playerDead = false

@IBOutlet var labelText: UILabel!

override func viewDidLoad() {
super.viewDidLoad()
} //end viewDidLoad

@IBAction func startGame(_ sender: Any) {
var playerOnePosition = locationArray.randomElement()!
var playerTwoPosition = locationArray.randomElement()!

while (playerDead != true) {
    playerOnePosition = locationArray.randomElement()!
    playerTwoPosition = locationArray.randomElement()!
    timeStamp += 1

    if playerOnePosition != playerTwoPosition {
    labelText.text = "(timeStamp) Player One is at (playerOnePosition) and Player Two is at (playerTwoPosition)"
     } //End first if statement

    if playerOnePosition == playerTwoPosition {
    labelText.text = "(timeStamp) They are in the same place."
    playerDead = true  //Game ends here
    } //End second if statement
 } //End while loop
 } //End function
 } //End class

通常输出的一个例子是13 他们在同一个地方",但我希望 UIlabel 打印导致 13 的所有其他时间戳"事件.

An example of usual output would be "13 They are in the same place", but I want the UIlabel to print all of the other "timestamp" events leading up to 13.

推荐答案

如果您想为每次 if 条件为真时添加新行文本,您需要追加文本并使用新行字符,

If you want to add a new line of text for each time an if condition is true you need to append the text and use a new line character,

while (playerDead != true) {
//...
    if playerOnePosition != playerTwoPosition {
        labelText.text = 
             (labelText.text ?? "" ) + 
             "(timeStamp) Player One is at (playerOnePosition) and Player Two is at (playerTwoPosition)
"
    }

    if playerOnePosition == playerTwoPosition {
        labelText.text = (labelText.text ?? "" ) + "(timeStamp) They are in the same place."
        playerDead = true  
    } 
}

还要让您的标签显示任意数量的行,请将限制设置为 0

Also to get your label to display any number of lines set the limit to 0

labelText.numberOfLines = 0

这篇关于在 While Loop Swift 中更新文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆