Swift iOS开发:如何将UICollectionView调整至自定义Navigation Bar下方?
修复自定义导航栏遮挡UICollectionView问题
核心问题为自定义导航栏采用硬编码frame计算位置,且未与UICollectionView做位置绑定,导致内容被遮挡,可按以下步骤修改:
- 重构自定义导航栏实现,改用自动布局适配全机型
修改后的addNavigationbar代码如下:
// 先把navBar声明为全局属性,方便后续给collectionView做约束绑定 var customNavBar: UINavigationBar! func addNavigationbar() { customNavBar = UINavigationBar() // 关闭自动生成约束,改用手动添加 customNavBar.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(customNavBar) // 添加导航栏约束 NSLayoutConstraint.activate([ customNavBar.leadingAnchor.constraint(equalTo: view.leadingAnchor), customNavBar.trailingAnchor.constraint(equalTo: view.trailingAnchor), customNavBar.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), customNavBar.heightAnchor.constraint(equalToConstant: 44) ]) let navigationItem = UINavigationItem(title: "") self.searchController = searchControllerWith(searchResultsController: nil) navigationItem.titleView = self.searchController.searchBar customNavBar.setItems([navigationItem], animated: false) self.definesPresentationContext = true }
- 绑定UICollectionView的顶部到自定义导航栏底部
如果你的UICollectionView用自动布局实现,添加如下约束即可:
// 记得把collectionView的translatesAutoresizingMaskIntoConstraints设为false NSLayoutConstraint.activate([ collectionView.topAnchor.constraint(equalTo: customNavBar.bottomAnchor), collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor), collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor), collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor) ]) // 可选:关闭系统自动调整滚动视图内边距,避免额外偏移 collectionView.contentInsetAdjustmentBehavior = .never
如果你的UICollectionView用frame布局,修改frame参数即可:
let collectionViewY = customNavBar.frame.maxY let collectionViewHeight = view.bounds.height - collectionViewY collectionView.frame = CGRect(x: 0, y: collectionViewY, width: view.bounds.width, height: collectionViewHeight)
原问题对应界面效果:
内容的提问来源于stack exchange,提问作者Lukas Bimba
相关产品推荐
相关产品推荐

