gpt4 book ai didi

swift - Collection View 选择和 DidDeselect 问题

转载 作者:行者123 更新时间:2023-11-30 10:34:30 25 4
gpt4 key购买 nike

我正在尝试更改 Collection View 的 didSelect 和 DidDeselect 委托(delegate)上的单元格文本字体,但它无法正常工作。最初,我希望我的第一个单元格文本字体为粗体,当用户点击任何其他单元格时,它应该更改点击的单元格字体,而其余单元格恢复为原始字体。这是我的代码,

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

let balanceData = balanceArray[indexPath.row]
self.recentTransactionArray.removeAll()
let selectedCell = currencyCVC.cellForItem(at: indexPath) as? CurrencyCVC
//self.index = indexPath

if indexPath != self.index
{
selectedCell?.amountLbl.font = UIFont.systemFont(ofSize:18, weight: .bold)
selectedCell?.currencyLbl.font = UIFont.systemFont(ofSize:22, weight: .bold)
selectedCell?.availableBalanceLbl.font = UIFont.systemFont(ofSize:11, weight: .bold)
selectedCell?.depositLbl.font = UIFont.systemFont(ofSize:11, weight: .bold)
}
else
{
selectedCell?.amountLbl.font = UIFont.systemFont(ofSize:18, weight: .medium)
selectedCell?.currencyLbl.font = UIFont.systemFont(ofSize:22, weight: .regular)
selectedCell?.availableBalanceLbl.font = UIFont.systemFont(ofSize:11, weight: .medium)
selectedCell?.depositLbl.font = UIFont.systemFont(ofSize:11, weight: .medium)
}
}

这是我的 DidDeselect 委托(delegate),

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
guard let cell = collectionView.cellForItem(at: indexPath) as? CurrencyCVC else {
return
}

if indexPath != self.index
{
DispatchQueue.main.async {
cell.amountLbl.font = UIFont.systemFont(ofSize:18, weight: .medium)
cell.currencyLbl.font = UIFont.systemFont(ofSize:22, weight: .regular)
cell.availableBalanceLbl.font = UIFont.systemFont(ofSize:11, weight: .medium)
cell.depositLbl.font = UIFont.systemFont(ofSize:11, weight: .medium)
}
}
}

现在,当我点击任何单元格时,它会更改当前单元格字体,但剩余单元格字体不会更改为原始字体。我怎样才能做到这一点?

最佳答案

尝试以下逻辑,执行起来非常简单

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
cell.title.text = arrData[indexPath.item].name

// setting different fonts when cell is selected & when unselected
cell.title.font = arrData[indexPath.item].isSelected ? UIFont.boldSystemFont(ofSize: 15) : UIFont.boldSystemFont(ofSize: 13)
return cell
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

// here setting all other selections false
arrData = arrData.compactMap{ return myModel(name: $0.name, isSelected: false) }

// then setting selected cell bit true
arrData[indexPath.row].isSelected = true

DispatchQueue.main.async {
collectionView.reloadData()
}
}

关于swift - Collection View 选择和 DidDeselect 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58371252/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com