【问题标题】:UICollectionView Horizontal align scroll first cell center alignment not exactly placing center position very first time using SwiftUICollectionView 水平对齐滚动第一个单元格中心对齐第一次使用 Swift 时不完全放置中心位置
【发布时间】:2019-06-17 14:33:51
【问题描述】:

我的场景,我正在尝试根据选择实现UICollectionView 水平scrollview 第一个和最后一个单元格中心对齐。在这里,第一次CollectionViewCell 第一个单元格没有显示确切的中心位置。如果我didselect 一切正常。 我需要修复第一次应用打开第一个单元格时没有显示确切的中心位置。

注意:我没有添加页眉和页脚,我也使用故事板完成了我的设计。

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let text = self.items[indexPath.row]
        let cellWidth = text.size(withAttributes:[.font: UIFont.systemFont(ofSize: 14.0)]).width + 10.0
        return CGSize(width: cellWidth, height: collectionView.bounds.height)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        let inset: CGFloat = collectionView.frame.width * 0.5 - 52 * 0.5
        return UIEdgeInsets(top: 0, left: inset, bottom: 0, right: inset)
    }

【问题讨论】:

  • 不能直接使用52,因为每个单元格的宽度都是动态的。

标签: ios swift uicollectionview


【解决方案1】:

您不能直接使用52,因为cell width,因为每个cellwidthdynamic

您需要根据firstlastcellactual width计算collectionViewleftInsetsrightInsets

您可以使用firstlastelementitems array 计算collectionView(_:layout:sizeForItemAt) 方法中相同的方式计算firstlast cellwidth,即

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    //Calculate width of first cell
    var firstCellWidth: CGFloat = 52.0
    if let textAtFirstIndex = self.items.first {
        firstCellWidth = textAtFirstIndex.size(withAttributes:[.font: UIFont.systemFont(ofSize: 14.0)]).width + 10.0
    }

    //Calculate width of last cell
    var lastCellWidth: CGFloat = 52.0
    if let textAtLastIndex = self.items.last {
        lastCellWidth = textAtLastIndex.size(withAttributes:[.font: UIFont.systemFont(ofSize: 14.0)]).width + 10.0
    }

    //Calculate leftInset and rightInset
    let leftInset: CGFloat = (collectionView.frame.width * 0.5) - (firstCellWidth * 0.5)
    let rightInset: CGFloat = (collectionView.frame.width * 0.5) - (lastCellWidth * 0.5)

    return UIEdgeInsets(top: 0, left: leftInset, bottom: 0, right: rightInset)
}

示例:

如果您仍然遇到任何问题,请告诉我。

【讨论】:

  • 太棒了。工作魅力。谢谢@PGDev
猜你喜欢
  • 2016-02-24
  • 2015-05-21
  • 2014-11-15
  • 2021-06-15
  • 1970-01-01
  • 2013-11-27
  • 1970-01-01
  • 2016-10-29
  • 1970-01-01
相关资源
最近更新 更多