【问题标题】:Getting the correct readableContentGuide after rotation旋转后获取正确的可读ContentGuide
【发布时间】:2020-07-18 16:08:18
【问题描述】:

我有一个嵌套的collectionView,我想在旋转后获取readableContentGuide,以便正确设置内容插入。

这就是它的样子:

我已经尝试对集合视图进行子类化并从layoutMarginsDidChangetraitCollectionDidChangelayoutSubviews 中获取值。

但是我得到的值总是以前的值(即当我处于纵向时,我得到横向值,反之亦然)

我也尝试在 collectionView 的collectionView(_:layout:insetForSectionAt:) 中设置插图。

目前,似乎唯一可行的解​​决方案是观察集合视图的边界,但这感觉有点 hacky。

对如何做到这一点有什么想法吗?

【问题讨论】:

    标签: ios swift iphone cocoa-touch uicollectionview


    【解决方案1】:

    如果您在情节提要上使用自动布局,您应该为超级视图激活“遵循可读宽度”选项。首先,确保集合视图附加到父视图的边距。然后去superview打开Size Inspector,选择选项:

    感谢马特the answer

    对于程序化自动布局,您不需要边距,只需将集合视图附加到父视图的 readableContentGuide 即可。像这样:

    let cv = collectionView
    
    // Guide of the superview
    let readableGuide = view.readableContentGuide 
    
    NSLayoutConstraint.activateConstraints([
        cv.topAnchor.constraintEqualToAnchor(readableGuide.topAnchor),
        cv.bottomAnchor.constraintEqualToAnchor(readableGuide.bottomAnchor),
        cv.rightAnchor.constraintEqualToAnchor(readableGuide.rightAnchor),
        cv.leftAnchor.constraintEqualToAnchor(readableGuide.leftAnchor)
    ])
    

    如果您更喜欢基于框架的程序化布局,您不需要使用父视图的layoutMarginsDidChangetraitCollectionDidChange,也不需要遵守bounds。布局代码的最佳位置是控制器的viewWillLayoutSubviews() func。这将处理任何边界变化,包括界面旋转。

    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
    
        collectionView.frame = view.readableContentGuide.layoutFrame
    
        collectionView.collectionViewLayout.invalidateLayout()
    }
    

    Here我解释了为什么我们需要invalidateLayout()

    【讨论】:

      猜你喜欢
      • 2016-02-28
      • 2018-11-20
      • 2012-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-19
      • 1970-01-01
      相关资源
      最近更新 更多