ios - 如何设置collectionview swift单元格的位置?

标签 ios swift

我正在使用 collectionview 全屏显示图像并允许在不同图像之间滚动。但是当方向改变时,它显示不正确。 Here image of screen after orientation change .这是我的代码

override func willRotate(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval) {


//    collectionView.reloadData()
    collectionView.collectionViewLayout.invalidateLayout()
    if visibleCell != nil {

     collectionView.selectItem(at: visibleCell as IndexPath?, animated: true, scrollPosition: .centeredHorizontally)

     }
}


func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return images.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCell", for: indexPath) as! ImageCollectionViewCell
        print(cell.frame)
      cell.SectionImage.image = images[indexPath.row].image

      return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    return CGSize(width: self.view.frame.width, height: self.view.frame.height)

}

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return 0
}

最佳答案

使用 UICollectionView sizeForItemAtIndexPath 方法定义单元格的高度和宽度。

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

    let leftAndRightPaddings: CGFloat = 15.0
    let numberOfItemsPerRow: CGFloat = CGFloat(NUMBER_OF_ITEMS_PER_ROW)

    let bounds = UIScreen.mainScreen().bounds
    let width = (bounds.size.width - leftAndRightPaddings * (numberOfItemsPerRow+1)) / numberOfItemsPerRow
    let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
    layout.itemSize = CGSizeMake(width, width)

    return layout.itemSize
}

尝试一下。您将获得预期的结果。

关于ios - 如何设置collectionview swift单元格的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42553042/

相关文章:

iphone - 有人使用 XMPP 在 iOS 上实现推送通知吗?

ios - 将值从 iOS native 代码传递到 cordova

objective-c - 是否有命令行界面可以列出Mac上范围内的所有蓝牙设备?

ios - 如何在 XR 手机上调整圆圈大小/修复约束

快速编程核心数据fetchedResultsController.sections nil错误

ios - 如何在ios中设置闹钟?

ios - 如何知道 AfNetworking 是否已下载所有图像

iphone - 用于跳转到方法实现的 Xcode 快捷方式?

ios - iOS11快速连续滑动删除UITableView单元格崩溃

ios - 如何在不指定年月日的情况下将 DateComponents 对象转换为本地化字符串,例如 "08:40 PM"?