gpt4 book ai didi

ios - 如何让 UILabel 每秒从 NSArray 中的每个项目更改文本然后再次旋转?

转载 作者:行者123 更新时间:2023-12-01 19:50:18 30 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Calling sleep(5); and updating text field not working

(4 个回答)



Objective C - loop to change label text

(4 个回答)


4年前关闭。




我想让我的 UILabel 每秒为数组中的每个项目更改文本(更改时淡入和淡出),然后在最后再次通过它。我试过了:

- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:YES];
NSArray *arrayOfText = @[@"Test1",@"Test2",@"Test3",@"Test4"];

for (int i = 0; i < [arrayOfText count]; i++) {

[NSThread sleepForTimeInterval:2.0f];

self.changingTextLabel.text = [arrayOfText objectAtIndex:i];

}


}

这将加载 ViewController,并在大约 8 秒后将文本更改为数组中的最后一项。

我究竟做错了什么?有一个更好的方法吗?在过去的几天里,我一直在寻找解决方案,但对我没有任何帮助。谢谢!

最佳答案

永远不要睡在主队列上。它会阻止您的应用程序的用户界面。

您有几个选择,但使用 NSTimer可能是最简单的。

向您的类添加几个实例变量:

@implementation WhateverViewController {
NSTimer *_labelTimer;
NSInteger labelIndex = 0;
}

- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:YES];

NSArray *arrayOfText = @[@"Test1",@"Test2",@"Test3",@"Test4"];

// Setup a timer to run every 2 seconds and update the label
// Increment the labelIndex so the next label is shown next time
_labelTimer = [NSTimer scheduledTimerWithTimeInterval:2.0 repeats:YES block:^(NSTimer *timer) {
self.changingTextLabel.text = arrayOfText[labelIndex];
labelIndex = (labelIndex + 1) % arrayOfText.count;
}];
}

- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];

// Stop the timer when we leave
[_labelTimer invalidate];
_labelTimer = nil;
}

- (void)dealloc {
// Make sure it is stopped
[_labelTimer invalidate];
}

关于ios - 如何让 UILabel 每秒从 NSArray 中的每个项目更改文本然后再次旋转?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46352180/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com