有时候我们设置了某些view的frame后,却并没有按照我们的设置去显示:
///MARK: - 懒加载
private lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kItemWidth, height: kItemHeight)
layout.minimumLineSpacing = kItemMargin
layout.minimumInteritemSpacing = kItemMargin
layout.headerReferenceSize = CGSize(width: kScreenWidth, height: 50)
layout.sectionInset = UIEdgeInsets(top: 0, left: kItemMargin, bottom: 0, right: kItemMargin)
let collectionView = UICollectionView.init(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.delegate = self
collectionView.dataSource = self
// collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
collectionView.backgroundColor = UIColor.white
collectionView.register(UINib.init(nibName: "NomalCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: kNomalID)
collectionView.register(UINib.init(nibName: "RecommendHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: kHeaderViewID)
return collectionView
}()
private lazy var cycleView : RecommendCycleView = {
let cycleView = RecommendCycleView.recommendCycleView()
// cycleView.autoresizingMask = []
cycleView.frame = CGRect(x: 0, y: -150, width: kScreenWidth, height: 150)
return cycleView
}()
如上 let collectionView = UICollectionView.init(frame: self.view.bounds, collectionViewLayout: layout) frame设置的是self.view.bounds,此时就有可能出现问题,有以下两种解决方法:
- 修改frame,用cgrect来写死
let collectionView = UICollectionView.init(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight - 88-50 - CGFloat(kTabbarHeight)), collectionViewLayout: layout)
- 第二种就是通过autoresizingMask,如上文,在frame为self.view.bounds时,要随着父view的大小改变而改变,添加如下代码,
// 自适应父view的宽高
collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
像下面我们在collectionView上添加了RecommendCycleView滚动视图,设置frame后拖拽并没有显示,是因为我们在collectionView上添加了autoresizingMask,若去掉就会显示,但去掉又会导致我们的collectionView的frame显示不正确,所以我们在RecommendCycleView中添加 cycleView.autoresizingMask = [] 取消自适应layout
以上是解决方法,但是为什么会有这样的现象,暂时还不太清楚,如有简友看到,欢迎指教。
网友评论