【问题标题】:IOS buttonClicked and updating a viewIOS按钮单击并更新视图
【发布时间】:2011-12-14 14:21:52
【问题描述】:

在 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];
}

【问题讨论】:

    标签: ios events uibutton


    【解决方案1】:

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

    // 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。

    这是一个相关的帖子:

    GCD, Threads, Program Flow and UI Updating

    【讨论】:

    • @Michael,非常感谢!您的 cmets 和相关帖子为我彻底清除了。
    • 应该是 bryanmac :) 但不客气。你必须稍微了解一下异步的东西......
    【解决方案2】:

    - (void)buttonClicked:(id)sender 将在主线程上被调用,所以当上下文已经是主线程时,为什么要使用 [letterlabel performSelectorOnMainThread:@selector(setTextColor:) withObject:[UIColor blackColor] waitUntilDone:YES]; 令人困惑。

    [letterlabel setBackgroundColor:[UIColor blackColor]]; 应该是您按下按钮时需要调用的全部内容。

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

    希望有帮助!

    【讨论】:

    • 你说得对,我误用了 performSelectorOnMainThread。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-13
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多