我正在尝试更改集合视图单元格标签的文本大小,并且可以工作一些。当我选择明智的项目索引(单元格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)
}
它在串联电池选择中起作用
但是当我随机选择单元格
谢谢,抱歉我的英语不好
答案 0 :(得分:1)
因为您重新创建了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)
}
}
答案 1 :(得分:1)
尝试一下...
var selectedCell = [Int]()
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: yourCellIdentifier, for: indexPath) as! MenuCell
//Code for change font size
if selectedCell.contains(indexPath.cell){
cell.title.font = UIFont.systemFont(ofSize: 16)
}else{
cell.title.font = UIFont.systemFont(ofSize: 13)
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if selectedCell.contains(indexPath.item){
selectedCell.remove(at: selectedCell.index(of: selectedCell.contains[indexPath.item])!)
}else{
selectedCell.append(indexPath.item)
}
collectionView.reloadData()
}