带有NSCollectionView的全宽NSCollectionViewFlowLayout

时间:2018-02-01 16:21:58

标签: objective-c macos nscollectionview nscollectionviewflowlayout

我有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:即使我收到警告/错误,布局宽度也有效,但我想找出潜在的问题。

3 个答案:

答案 0 :(得分:0)

这是因为您使用的是didResize事件,为时已晚。窗口开始收缩时,您的物品太宽。尝试使用:

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

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

答案 1 :(得分: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+

答案 2 :(得分:0)

我遇到了同样的问题,但就我而言,我调整了视图的大小。在更改无效上下文之前,@ 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
    }
}

希望这对某人有帮助,因为我花了两个晚上才找到解决方法