iOS:从运行循环外部设置UIView背景颜色

时间:2010-11-05 03:22:42

标签: iphone ipad ios

我希望在专用于音频的线程中运行的事件能够更改UI。简单地调用view.backgroundColor似乎没有任何效果。

我的viewController中有两个方法。第一个是触摸触发。第二个是从音频代码中调用的。第一部作品。第二。知道为什么吗?

// this changes the color
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    [touchInterpreter touchesMoved:touches withEvent:event];
    self.view.backgroundColor = [UIColor colorWithWhite: 0.17 + 2 *  [patch getTouchInfo]->touchSpeed alpha:1];

};

// this is called from the audio thread and has no effect
-(void)bang: (float)intensity{
    self.view.backgroundColor = [UIColor colorWithWhite: intensity alpha:1];
}

知道为什么吗?我只是做了一些愚蠢的事情,还是有一个从运行循环外部更改UI元素的技巧?

1 个答案:

答案 0 :(得分:6)

不允许从主线程以外的任何其他方式触摸UI,并且会导致奇怪的行为或崩溃。在iOS 4.0或更高版本中,您应该使用类似

的内容
- (void)bang:(float)intensity {
    dispatch_async(dispatch_get_main_queue(), ^{
        self.view.backgroundColor = [UIColor colorWithWhite:intensity alpha:1];
    });
}

或NSOperationQueue变体

- (void)bang:(float)intensity {
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        self.view.backgroundColor = [UIColor colorWithWhite:intensity alpha:1];
    }];
}

在iOS 3.2或更早版本中,您可以使用[self performSelectorOnMainThread:@selector(setViewBackgroundColor:) withObject:[UIColor colorWithWhite:intensity alpha:1] waitUntilDone:NO],然后只需定义

- (void)setViewBackgroundColor:(UIColor *)color {
    self.view.backgroundColor = color;
}

请注意,调用[self.view performSelectorOnMainThread:@selector(setBackgroundColor:) withObject:[UIColor colorWithWhite:intensity alpha:1] waitUntilDone:NO]并不安全,因为UIViewController的view属性不是线程安全的。