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

查看:78
本文介绍了在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?

我查看了此链接,但是该示例似乎与我的情况不符,并且不确定如何实施此修复程序(如果正确的话):

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条件为true时每次添加新行,则需要追加文本并使用换行符\ n

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, \n

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

    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天全站免登陆