我試圖調整我的collectionViewCells每次我旋轉設備,但我不能弄清楚如何。這是我的問題和我的代碼。這是一個在夫特3和的Xcode 8.如何在設備旋轉時自動調整UICollectionView的大小?
在另一方面,如果我當設備旋轉(橫向)時加載firstScreen(HomePage),然後再次將設備旋轉到Portrait,單元格溢出,所以我不能看到它們的側面。因爲寬度仍然與橫向寬度相同。
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return allNews.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath) as! HomeCollectionViewCell
// Configure the cell
cell.imageView.image = allNews[indexPath.row].newsPic
cell.textView.text = allNews[indexPath.row].newsTitle
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let height = (view.frame.width - 32) * 9/16
return CGSize(width: view.frame.width, height: height + 94)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
// MARK: Orientation Changes (reload the CollectionLayout)
override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) {
}
最後,我沒有在Main.storyboard中使用Auto-Layout。這裏是HomeCollectionViewCell類
private func setupViews() {
addSubview(imageView)
addSubview(textView)
addSubview(separatorView)
addSubview(dateView)
addConstraintsWithFormat(format: "H:|-16-[v0]-16-|", views: imageView)
addConstraintsWithFormat(format: "V:|-16-[v0]-8-[v1(40)]-2-[v2(20)]-8-|", views: imageView, textView, dateView)
addConstraintsWithFormat(format: "H:|-16-[v0]-16-|", views: textView)
addConstraintsWithFormat(format: "H:|-16-[v0]-16-|", views: dateView)
addConstraintsWithFormat(format: "H:|[v0]|", views: separatorView)
addConstraintsWithFormat(format: "V:[v0(1)]|", views: separatorView)
}
問候我setupViews()方法。
解決!:我用這個方法,而不是覆蓋FUNC didRotate(從fromInterfaceOrientation:UIInterfaceOrientation){}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
collectionView?.collectionViewLayout.invalidateLayout()
}
您是否在使用自動佈局形式故事板或筆尖? –
感謝您的解決方案,這對我有用 - swift 3 xcode 8.3.1部署目標iOS 10.0 – Jeeves