UICollectionViewCell插入不更新

时间:2019-03-29 09:30:47

标签: ios uicollectionviewcell

我有一个UICollectionview,它的一个单元格将根据字符串调整宽度。但是,每次选择单元格时,插图都是不一致的。

例如

这是我的UICollectionView,它根据选择显示最近的情况

enter image description here

当我单击 Test 时,它将显示在顶部,但插图不一致。

enter image description here

当我单击 绘画 时,它到达顶部,但插图仍然不相同。

enter image description here

我已经尝试 -layoutIfNeeded()invalidateLayout,但仍然无法正常工作。

这就是我控制尺寸和插图的方式。

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    guard let view = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as? RecentSearchesCollectionViewCell else { fatalError("Cell not found.") }
    let recentSearch = recentSearches?[indexPath.row]
    view.configure(recentSearch?.name ?? "")
    view.layoutIfNeeded()
    return view
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let font = UIFont.systemFont(ofSize: 16)
    let string = recentSearches?[indexPath.row].name
    let size = string?.widthWithConstraintHeight(41, font: font) ?? 0
    return CGSize(width: size + 10, height: 41)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    return UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
}

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

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

extension String {
    func widthWithConstraintHeight(_ height: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: CGFloat.greatestFiniteMagnitude, height: height)
        let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font: font], context: nil)
        return boundingBox.width
    }
}

0 个答案:

没有答案