【发布时间】:2016-12-02 08:21:00
【问题描述】:
每次我旋转设备时,我都在尝试调整我的 collectionViewCells 的大小,但我不知道该怎么做。这是我的问题和我的代码。它在 Swift 3 和 Xcode 8 中。
另一方面,如果我在设备旋转(横向)时加载 firstScreen(HomePage),然后我再次将设备旋转到纵向,单元格会溢出,所以我看不到它们的侧面。因为宽度仍然与横向宽度相同。
// 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 中使用自动布局。这是我在 HomeCollectionViewCell 类中的 setupViews() 方法
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)
}
问候。
已解决!:我使用了这个方法而不是 override func didRotate(from 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