Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/107.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
IOS按钮单击并更新视图_Ios_Events_Uibutton - Fatal编程技术网

IOS按钮单击并更新视图

IOS按钮单击并更新视图,ios,events,uibutton,Ios,Events,Uibutton,在buttonClicked方法中,我想将UILabel中文本的颜色设置为黑色,等待三秒钟,然后将颜色设置为绿色。但是,标签从不变黑。该方法等待三秒钟,然后UILabel文本变为绿色。我原以为使用performSelectorOnMainThread可以解决这个问题,但事实并非如此。代码如下。事先非常感谢,如果我遗漏了一些明显的东西,请道歉 乔恩R -(void) buttonClicked: (id) sender { // (UILabel *) letterLabel is ins

在buttonClicked方法中,我想将UILabel中文本的颜色设置为黑色,等待三秒钟,然后将颜色设置为绿色。但是,标签从不变黑。该方法等待三秒钟,然后UILabel文本变为绿色。我原以为使用performSelectorOnMainThread可以解决这个问题,但事实并非如此。代码如下。事先非常感谢,如果我遗漏了一些明显的东西,请道歉

乔恩R

-(void) buttonClicked: (id) sender
{
    // (UILabel *) letterLabel is instance variable of TestProgramDelegate

    [letterlabel performSelectorOnMainThread:@selector(setTextColor:) withObject:[UIColor blackColor] waitUntilDone:YES];

    [NSThread sleepForTimeInterval:3];

    [letterLabel performSelectorOnMainThread:@selector(setTextColor:) withObject: [UIColor greenColor] waitUntilDone:YES];
}

您的方法是同步更改颜色两次。所有这些代码都在主线程上执行

// run on main thread
[letterlabel performSelectorOnMainThread:@selector(setTextColor:) withObject:[UIColor blackColor] waitUntilDone:YES];

// buttonClicked: called on mainThread so this is on main thread
[NSThread sleepForTimeInterval:3];

// also on main thread ...
[letterLabel performSelectorOnMainThread:@selector(setTextColor:) withObject: [UIColor greenColor] waitUntilDone:YES];
UI主线程正在循环,并根据按钮单击等情况查找要触发的代码。一旦检测到单击,您的方法就会执行,设置颜色,等待三秒钟,然后再次设置颜色,然后UI主循环才能重新绘制。由于UI不会在两者之间重新绘制,因此您永远不会看到第一个

如果您想这样做,您需要设置颜色,然后在背景线程上,等待三秒钟,然后调用主线程更新UI

这是一个相关的帖子:

主线程将调用
-(void)按钮:(id)sender
,因此您使用
[letterlabel performselectornmainthread:@selector(setTextColor:)with object:[UIColor blackColor]waituntldone:YES]的原因很混乱当上下文已经是主线程时

// run on main thread
[letterlabel performSelectorOnMainThread:@selector(setTextColor:) withObject:[UIColor blackColor] waitUntilDone:YES];

// buttonClicked: called on mainThread so this is on main thread
[NSThread sleepForTimeInterval:3];

// also on main thread ...
[letterLabel performSelectorOnMainThread:@selector(setTextColor:) withObject: [UIColor greenColor] waitUntilDone:YES];
[letterlabel setBackgroundColor:[UIColor blackColor]]

您可以使用NSTimer或本地通知回调将颜色更改为绿色。在应用程序中让主线程休眠通常不是一个好主意


希望有帮助

@Michael,非常感谢!你的评论和相关帖子为我彻底澄清了这一点。应该是bryanmac:)但不客气。你必须稍微考虑一下异步的东西……你是对的,我误用了performselectornmainthread。谢谢你的帮助!