我想知道 Apple 的 -setNeedsLayout
是如何工作的。
我已经知道它比直接调用 -layoutSubviews
更有效,因为我可能需要在一个方法中执行两次。
这正是我需要它的目的:一些自定义 -setNeedsValidation
用于 View Controller 。
但是如何实现这样的功能呢?
最佳答案
我无法确认 Apple 是否正是这样做的,但这里有一种方法可以满足您的需求,并且可能类似于 setNeedsLayout
的实现方式。我还没有对此进行测试(甚至没有对其进行编译),但它应该给出了如何将问题作为 UIViewController
上的一个类别来解决的想法。与 UIKit 一样,这是完全线程不安全的。
static NSMutableSet sViewControllersNeedingValidation = nil;
static BOOL sWillValidate = NO;
@implementation UIViewController (Validation)
+ (void)load {
sViewControllersNeedingValidation = [[NSMutableSet alloc] init];
}
- (void)setNeedsValidation {
[sViewControllersNeedingValidation addObject:self];
if (! sWillValidate) {
sWillValidate = YES;
// Schedule for the next event loop
[[self class] performSelector:@selector(dispatchValidation) withObject:nil afterDelay:0];
}
}
+ (void)dispatchValidation {
sWillValidate = NO;
// The copy here is in case any of the validations call setNeedsValidation.
NSSet *controllers = [sViewControllersNeedingValidation copy];
[sViewControllersNeedingValidation removeAllObjects];
[controllers makeObjectsPerformSelector:@selector(validate)];
[controllers release];
}
- (void)validate {
// Empty default implementation
}
关于objective-c - setNeedsLayout 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7794185/