UICollectionView 水平对齐滚动第一个单元格中心对齐方式第一次使用 Swift 时未准确放置中心位置

Jam*_* Ku 3 ios uicollectionview swift

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

\n\n

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

\n\n
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {\n        let text = self.items[indexPath.row]\n        let cellWidth = text.size(withAttributes:[.font: UIFont.systemFont(ofSize: 14.0)]).width + 10.0\n        return CGSize(width: cellWidth, height: collectionView.bounds.height)\n    }\n\n    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {\n        let inset: CGFloat = collectionView.frame.width * 0.5 - 52 * 0.5\n        return UIEdgeInsets(top: 0, left: inset, bottom: 0, right: inset)\n    }\n
Run Code Online (Sandbox Code Playgroud)\n

PGD*_*Dev 6

您不能直接使用52since作为the cell width,因为width每个的thecelldynamic

您需要根据和计算leftInsets和。rightInsetscollectionViewactual widthfirstlast cell

您可以使用and of来计算widthoffirst和,last cell就像在collectionView(_:layout:sizeForItemAt)method中所做的那样,即firstlast elementitems array

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)
}
Run Code Online (Sandbox Code Playgroud)

例子:

在此输入图像描述

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