繁体   English   中英

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

[英]iOS: setting UIView background color from outside the run loop

我希望在专用于音频的线程中运行的事件能够改变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元素的技巧?

不允许从主线程以外的任何其他方式触摸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属性不是线程安全的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM