iOS:从运行循环外部设置UIView背景颜色
问题描述:
我想要在专用于音频的线程中运行的事件来更改UI。简单地调用view.backgroundColor似乎没有任何效果。iOS:从运行循环外部设置UIView背景颜色
这里是我的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元素?
答
从主线程以外的任何地方触摸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
属性不是线程安全的。
非常感谢! – morgancodes 2010-11-05 12:48:36