1.哪个view的frame偏移就给它添加一个观察者,KVO很简单,在此不用多说
for (UIView *subView in self.view.subviews) {
if ([subView isKindOfClass:NSClassFromString(@"UITransitionView")]) {
_transitionView = subView;
self.noTransitionFrame = subView.frame.size.height;
[_transitionView addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionNew context:nil];(发生偏移的view,给它添加观察者)
break;
}
}
2.监听它的frame发生改变时,强制改回来,noTransitionFrame是一开始不发生偏移的
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if([keyPath isEqualToString:@"frame"])
{
NSValue *newStr = change[@"new"];
CGRect newRect = [newStr CGRectValue];
if (newRect.size.height != self.noTransitionFrame) {
newRect.size.height = self.noTransitionFrame;
_transitionView.frame = newRect;
}
NSLog(@"%@", change);
}
}
3.最后别忘了移除观察者
- (void)dealloc{
[_transitionView removeObserver:self forKeyPath:@"frame"];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}