代码之家  ›  专栏  ›  技术社区  ›  David Hoerl

如何修复键盘来来去去时的“UICollectionViewFlowLayout未定义”

  •  0
  • David Hoerl  · 技术社区  · 2 年前

    完整的信息是: The behavior of the UICollectionViewFlowLayout is not defined because: the item height must be less than the height of the UICollectionView minus the section ...

    在可能的情况下,水平集合视图会填充视图的底部。当键盘关闭时,我会收到大量以上信息。我观察到 contentSize 的集合视图更改为一些非常小的数字。但我所做的一切都无法让它停止抱怨:当 contentSize 改变。

    1 回复  |  直到 2 年前
        1
  •  0
  •   David Hoerl    2 年前

    最终起作用的是,从键盘开始移动到完全隐藏,抑制使布局无效的消息。目标应用程序是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 消息已发送到此对象。