ios - 更改 UICollectionView 中选定单元格的文本大小

标签 ios swift uicollectionview

我正在尝试更改 Collection View 单元格标签的文本大小并稍微起作用。当我明智地选择项目索引(单元格 0、单元格 1、单元格 2....)时,它对我有用但是当我尝试在随机索引上选择项目(例如:单元格 0 到单元格 3)时,我的应用程序崩溃了

我正在尝试这段代码:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)  {
    let idxPath = IndexPath(item: indexPath.item, section: 0)
    let cell = collectionView.cellForItem(at: idxPath)
    let myCell = collectionView.cellForItem(at: idxPath) as! MenuCell
    cell?.isSelected = true
    myCell.isSelected = true
    myCell.title.font = UIFont.systemFont(ofSize: 16)
    collectionView.scrollToItem(at: idxPath, at: UICollectionViewScrollPosition.centeredHorizontally, animated: true)
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
    let idxPath = IndexPath(item: indexPath.item, section: 0)
    let myCell = collectionView.cellForItem(at: idxPath) as! MenuCell
    myCell.isSelected = false
    myCell.title.font = UIFont.systemFont(ofSize: 13)
}

它在串联电池选择中起作用

enter image description here

但是当我随机选择单元格时

enter image description here

谢谢,抱歉我的英语不好

最佳答案

因为您重新创建了 IndexPath,然后对单元格强制展开。 如果您只需要为第一部分更改字体,请尝试像这样更改代码:

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
    if indexPath.section == 0 {
      let myCell = collectionView.cellForItem(at: indexPath) as? MenuCell
       myCell?.isSelected = false
       myCell?.title.font = UIFont.systemFont(ofSize: 13)
    }
}

关于ios - 更改 UICollectionView 中选定单元格的文本大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51498141/

相关文章:

ios - 如何在 iOS swift 的 ARSCNView 中显示 uicollection View

ios - 如何触发Core Bluetooth状态保存和恢复

ios - 在 Swift (iOS) 中隐藏一个元素并占用它的空间

Swift UIRefreshControl 到 UIScrollView 内的 UICollectionView

ios - 如何用断点导航器中的定义替换 NSUncaughtExceptionHandler?

ios - 使用 Alamofire 上传图像的问题(有图像作为参数)

ios - 如何通过生成 pdf 的缩略图来预加载 CollectionView 中的图像?

ios - removefromsuperview 和 addsubview 不改变显示

ios - SQLite.swift - 无法为 Row 类型的值添加下标。 swift 2

iphone - 调整 TableViewCell 大小以适应 RSS Feed 详细信息