最终起作用的是,从键盘开始移动到完全隐藏,抑制使布局无效的消息。目标应用程序是Objective-C,但转换为Swift并不重要。
@interface SSCollectionViewFlowLayout : UICollectionViewFlowLayout
@property (nonatomic, assign) BOOL shouldSuppress;
@end
@implementation SSCollectionViewFlowLayout
- (instancetype)initWithCoder:(NSCoder *)coder {
self = [super initWithCoder:coder];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardUp)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardDown)
name:UIKeyboardWillHideNotification
object:nil];
return self;
}
- (void)keyboardUp {
self.shouldSuppress = YES;
}
- (void)keyboardDown {
self.shouldSuppress = NO;
}
- (void)prepareLayout {
if(self.shouldSuppress) { return; }
[super prepareLayout];
}
- (void)invalidateLayout {
if(self.shouldSuppress) { return; }
[super invalidateLayout];
}
- (void)invalidateLayoutWithContext:(UICollectionViewLayoutInvalidationContext *)context {
if(self.shouldSuppress) { return; }
[super invalidateLayoutWithContext:context];
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
两者
invalidate
消息已发送到此对象。