Swift:水平设置UICollectionView的单元格左对齐

时间:2018-11-07 08:51:49

标签: swift uicollectionview

我有一个collectionView,其中的单元格具有动态宽度。问题是单元格在中心对齐,我希望它在左侧对齐,看图片,在要对齐的位置画了一条红线:

Screen

这是我的收藏夹视图配置:

var collectionView: UICollectionView = {
    let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    layout.itemSize = CGSize(width: 100, height: 40)
    layout.scrollDirection = .horizontal
    layout.minimumLineSpacing = 0

    let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
    collectionView.setCollectionViewLayout(layout, animated: true)
    collectionView.register(SportsCell.self, forCellWithReuseIdentifier: "MyCell")
    collectionView.translatesAutoresizingMaskIntoConstraints = false
    collectionView.backgroundColor = .white
    collectionView.showsHorizontalScrollIndicator = false

    return collectionView
}()

然后使用使大小动态化的方法:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let text = items[indexPath.row].message
    let padding: CGFloat = 5

    return CGSize(width: textWidth(text: text, font: .systemFont(ofSize: 22)) + padding, height: 40)
}

func textWidth(text: String, font: UIFont?) -> CGFloat {
    let attributes = font != nil ? [NSAttributedString.Key.font: font!] : [:]
    return text.size(withAttributes: attributes).width
}

0 个答案:

没有答案