如果视图的属性设置在 iOS 中的不同线程上,如何刷新视图

How to refresh the view if its properties are set on a different thread in iOS

各位,

我创建了一个线程,并在该线程中调用了一个对象(称为 myGenerator)的方法来为我生成一些整数值。

每次新值来自 myGenerator 的委托方法时,我都会更改主视图控制器中 UIButton 的宽度值。

按钮的宽度值按计划不断变化,但按钮的宽度在视觉上没有变化。

每次更改后我都使用了setNeedsDisplay方法,但没有任何反应。 知道如何在第二个线程更改按钮宽度时在视觉上刷新它吗?

(请注意,我需要在单独的线程中获取新值)。

谢谢。

-(void) aMethod:{
//I use this method to create a new thread for 
//getting new integer values produced in myGenerator object.

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
            [self.myGenerator ProduceAnewValueForButtonWidth];
        });
}


-(void) ValueIsReady{
//This is a delegate method which is fired 
//each time the myGenerator object generates a 
//new value for button's width via the thread above.

    [self.button setBounds:CGRectMake(180, 130, self.myGenerator.producedValue, 50 )];
    [self.button setNeedsDisplay];
    NSLog(@"value = %.4f, %.4f", self.myGenerator.producedValue, self.button.bounds.size.width);

}

您需要在主线程中更新您的 UI:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^(void){
    //Background Thread
    [self.myGenerator ProduceAnewValueForButtonWidth];

    dispatch_async(dispatch_get_main_queue(), ^(void){
        //Run UI Updates
        //Update your button width here

    });
});