gpt4 book ai didi

ios - 如何更新 UI,等待一段时间并在 iOS 中使用线程再次更新它?

转载 作者:行者123 更新时间:2023-11-28 20:03:49 25 4
gpt4 key购买 nike

我有一个应用程序,我需要一个带有文本“Hello”的蓝色按钮来发出红光并显示“Alert”一词。然后恢复为蓝色并发送文本“你好”。我该怎么做?

我知道如何将线程用于基于模型的任务,但不知道如何将线程用于基于 UI 的任务,这显然必须在主线程上进行。不过我不太擅长使用积木。

基本上我想做的是这个(伪代码):

- (void) animateUIAndRevertAfterSomeTime
{
// update button title to @"Alert" using setTitle: forState:
[self.thisButton setTitle: @"Alert" forState:UIControlStateNormal;
// set buttons' backgroundColor to redColor
self.thisButton.backgroundColor = [UIColor redColor];

// start timer for 10 seconds
// once time is up
{
// update button title to @"Hello" using setTitle: forState:
[self.thisButton setTitle: @"Hello" forState:UIControlStateNormal;
// set button's backgroundColor to blueColor
self.thisButton.backgroundColor = [UIColor blueColor];
}
}

任何人都可以在 Objective-C 中执行上述操作而不挂起应用程序界面 10 秒吗? :P

最佳答案

performSelector:withObject:afterDelay:可以这样做:

- (void) animateUIAndRevertAfterSomeTime
{
// update button title to @"Alert" using setTitle: forState:
[self.thisButton setTitle: @"Alert" forState:UIControlStateNormal;
// set buttons' backgroundColor to redColor
self.thisButton.backgroundColor = [UIColor redColor];
// start timer for 10 seconds
// once time is up
[self performSelector:@selector(updateButton) withObject:nil afterDelay:10];
}


-(void)updateButton
{
// update button title to @"Hello" using setTitle: forState:
[self.thisButton setTitle: @"Hello" forState:UIControlStateNormal];
// set button's backgroundColor to blueColor
self.thisButton.backgroundColor = [UIColor blueColor];
}

或者你可以使用 NSTimer 来实现同样的事情:

[NSTimer scheduledTimerWithTimeInterval:10
target:self
selector:@selector(updateButton)
userInfo:nil
repeats:NO];

关于ios - 如何更新 UI,等待一段时间并在 iOS 中使用线程再次更新它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22895952/

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