【发布时间】:2020-02-05 02:55:18
【问题描述】:
我有一个完整的页面 UICollectionViewCell,一旦开始滚动,下一个 indexPath 的数据就会被打印出来。这在我的项目中造成了问题,因为即使它几乎没有被拖动,下一个 indexPath 也会被打印出来,并且我的 UICell 中有一个 UIButton,我希望在按下它后立即隐藏它。但是我只希望它隐藏在那个特定的单元格中。由于某种原因,它现在被隐藏在我的 collectionView 的不同索引中。任何事情都会有所帮助,谢谢。
class CollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
init() {
super.init(collectionViewLayout: UICollectionViewFlowLayout())
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private var collectionViewFlowLayout: UICollectionViewFlowLayout {
return collectionViewLayout as! UICollectionViewFlowLayout
}
override func viewDidLoad() {
collectionView.showsHorizontalScrollIndicator = false
collectionView.showsVerticalScrollIndicator = false
collectionViewFlowLayout.minimumLineSpacing = 0
self.collectionView.isPagingEnabled = true
if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
layout.scrollDirection = .horizontal
}
collectionView?.register(PostCell.self, forCellWithReuseIdentifier: cellId)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let screenSize = UIScreen.main.bounds.size
return screenSize
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return itemsArr.count
}
var totalPrice = Double()
@objc func buttonPressed(_ sender : UIButton){
let item = itemsArr[sender.tag].price
totalPrice += Double(item) ?? 0
sender.isHidden = true
print(item)
print(totalPrice)
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! PostCell
let item = itemsArr[indexPath.row]
cell.set(name: item.name, brand: item.brand, price: item.price)
cell.myButton.tag = indexPath.row
cell.myButton.addTarget(self, action: #selector(buttonPressed(_:)), for: .touchUpInside)
return cell
}
}
【问题讨论】:
-
在我看来,你应该为 buttonPressed 使用委托,当用户按下按钮时,你可以获得索引单元格并更新“itemArr”中的单元格数据(在 obj 项目中添加 var“isHidden”)。更新数据完成后,您应该重新加载 collectionview 或重新加载单元格。
-
使用可以试试 cell.myButton.isHidden = item.isHidden
标签: ios swift uicollectionview