【发布时间】:2017-05-07 15:56:50
【问题描述】:
我正在使用UICollectionview 创建 7 个单元格。当我滚动时,应用程序工作正常,但如果我继续滚动,它开始滞后并且阴影(每个单元格后面)变得更暗。
我认为从屏幕上消失的单元格不会被删除,当我返回时,程序会在最旧的单元格的相同位置重新创建一个新单元格。有什么解决办法吗?
滚动前的画面
滚动后的屏幕
这是代码
class menuController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
@IBOutlet weak var coll_view: UICollectionView!
var array = [String]()
override func viewDidLoad() {
array = ["segue_menu_map", "segue_menu_camera"]
coll_view.scrollToItem(at: IndexPath(item: 2, section: 0), at: .left, animated: true)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 7
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
let button = UIButton(type: .custom)
button.frame = CGRect(x: 0, y: 0, width: cell.frame.width, height: cell.frame.height)
button.layer.cornerRadius = 0.2*button.frame.width
button.backgroundColor = UIColor.white
button.layer.borderWidth = 2
button.tag=indexPath.row
button.layer.shadowColor = UIColor.lightGray.cgColor
button.layer.shadowOpacity = 1.0
button.layer.shadowOffset = CGSize(width: 0.4, height: 1.8)
cell.clipsToBounds = false
button.addTarget(self, action: #selector(collectionAction(sender:)), for: .touchUpInside)
print([indexPath.row])
//cell.backgroundColor = UIColor.gray
button.setTitle(String(indexPath.row), for: .normal)
button.setTitleColor(.black, for: .normal)
cell.addSubview(button)
return cell
}
func collectionAction( sender: UIButton) {
if sender.tag < 2{
self.performSegue(withIdentifier: array[sender.tag], sender: nil)
}
}
}
提前致谢
【问题讨论】:
-
从
viewDidLoad函数调用super.viewDidLoad()。此外,collectionViewCells被重用,并且因为您是cellForRowAt中的按钮,它可能不会从视图层次结构中删除。您是否为单元格覆盖了prepareForReuse? -
不,我没有。我该怎么做?
-
我强烈建议您查看这个答案:stackoverflow.com/questions/31735228/…
标签: ios swift uicollectionview cell