8

我有一个NSCollectionViewFlowLayout包含以下内容:

- (NSSize) itemSize
{
    return CGSizeMake(self.collectionView.bounds.size.width, kItemHeight);
} // End of itemSize

- (CGFloat) minimumLineSpacing
{
    return 0;
} // End of minimumLineSpacing

- (CGFloat) minimumInteritemSpacing
{
    return 0;
} // End of minimumInteritemSpacing

我已经尝试过使布局响应的方法(在调整大小时设置宽度)。我尝试添加以下内容:

[[NSNotificationCenter defaultCenter] addObserver: self
                                         selector: @selector(onWindowDidResize:)
                                             name: NSWindowDidResizeNotification
                                           object: nil];

- (void) onWindowDidResize: (NSNotification*) notification
{
    [connectionsListView.collectionViewLayout invalidateLayout];
} // End of windowDidResize:

如果我扩展集合视图(调整更大),这会很好。但是,如果我尝试折叠视图(缩小尺寸),则会出现以下异常:

The behavior of the UICollectionViewFlowLayout is not defined because:
The item width must be less than the width of the UICollectionView minus the section insets left and right values, minus the content insets left and right values.
The relevant UICollectionViewFlowLayout instance is <TestListLayout: 0x106f70f90>, and it is attached to <NSCollectionView: 0x106f76480>.

关于如何解决这个问题的任何建议?

注意 1:这是 macOS 而不是 iOS(即使错误消息指出 UICollectionViewFlowLayout)。

注意 2:即使我收到警告/错误,布局宽度仍然有效,但我想找出根本问题。

4

3 回答 3

1

我遇到了同样的问题,但就我而言,我调整了视图的大小。在我更改失效上下文之前,@Giles 解决方案对我不起作用

class MyCollectionViewFlowLayout: NSCollectionViewFlowLayout {

    override func shouldInvalidateLayout(forBoundsChange newBounds: NSRect) -> Bool {
        return true
    }

    override func invalidationContext(forBoundsChange newBounds: NSRect) -> NSCollectionViewLayoutInvalidationContext {
       let context = super.invalidationContext(forBoundsChange: newBounds) as! NSCollectionViewFlowLayoutInvalidationContext
       context.invalidateFlowLayoutDelegateMetrics = true
       return context
    }
}

希望它对某人有所帮助,因为我花了几个晚上才找到解决方案

于 2020-10-09T20:34:42.997 回答
0

这是因为您正在使用 didResize 事件,这为时已晚。在窗口开始缩小的那一刻,您的项目太宽了。尝试使用:

func shouldInvalidateLayout(forBoundsChange newBounds: NSRect) -> Bool {
    return true
}

...当覆盖流布局时,重新计算所有内容。

于 2018-03-23T09:08:38.210 回答
0

我在问题中发布的源代码从 macOS 10.14 开始运行良好,没有任何问题。我将以下内容添加到显示集合视图的窗口中。

// Only Mojave and after is resizable. Before that, a full sized collection view caused issues as listed
// at https://stackoverflow.com/questions/48567326/full-width-nscollectionviewflowlayout-with-nscollectionview
if(@available(macOS 10.14, *))
{
    self.window.styleMask |= NSWindowStyleMaskResizable;
} // End of macOS 10.14+
于 2019-04-15T17:52:13.937 回答