我希望在专用于音频的线程中运行的事件能够改变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];
}
Run Code Online (Sandbox Code Playgroud)
知道为什么吗?我只是做了一些愚蠢的事情,还是有一个从运行循环外部更改UI元素的技巧?
不允许从主线程以外的任何其他方式触摸UI,并且将导致奇怪的行为或崩溃.在iOS 4.0或更高版本中,您应该使用类似的东西
- (void)bang:(float)intensity {
dispatch_async(dispatch_get_main_queue(), ^{
self.view.backgroundColor = [UIColor colorWithWhite:intensity alpha:1];
});
}
Run Code Online (Sandbox Code Playgroud)
或NSOperationQueue变体
- (void)bang:(float)intensity {
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
self.view.backgroundColor = [UIColor colorWithWhite:intensity alpha:1];
}];
}
Run Code Online (Sandbox Code Playgroud)
在iOS 3.2或更早版本中,您可以使用[self performSelectorOnMainThread:@selector(setViewBackgroundColor:) withObject:[UIColor colorWithWhite:intensity alpha:1] waitUntilDone:NO]然后定义
- (void)setViewBackgroundColor:(UIColor *)color {
self.view.backgroundColor = color;
}
Run Code Online (Sandbox Code Playgroud)
请注意,调用[self.view performSelectorOnMainThread:@selector(setBackgroundColor:) withObject:[UIColor colorWithWhite:intensity alpha:1] waitUntilDone:NO]不安全,因为viewUIViewController 的属性不是线程安全的.
| 归档时间: |
|
| 查看次数: |
15834 次 |
| 最近记录: |