iOS:如何在运行循环之外设置UIView的背景颜色

3

我希望在一个专门用于音频的线程中运行的事件可以改变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个回答

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属性不是线程安全的。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接