Reputation: 121
I am creating 7 cells using UICollectionview
. When i scroll, the application works fine, but if i continue to scroll, it start to lag and the shadow(behind every cell) become more dark.
I think that the cell that disappear from the screen is not deleted and when i return back the program recreate a new one in the same position of the oldest one. is there any solution?
Screen before the scroll
Scree after the scroll
here's the code
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)
}
}
}
thanks in advance
Upvotes: 1
Views: 1138
Reputation: 361
I faced the same problem when i am scrolling the collectionView. I had found two major problem and fixed this.
And add this code in custom cell or cellforItem in main class:
for main class
cell.layer.shadowPath = [UIBezierPath bezierPathWithRoundedRect:cell.bounds cornerRadius:cell.contentView.layer.cornerRadius].CGPath;
for custom cell
self.layer.shadowPath = [UIBezierPath bezierPathWithRoundedRect:cell.bounds cornerRadius:cell.contentView.layer.cornerRadius].CGPath;
Upvotes: 0
Reputation: 33979
collectionView.dequeueReusableCell
does not create a new cell every time. It reuses already created cells to improve performance. You are adding a button to the cell every time it's reused, this could mean that a single cell could have dozens/hundreds of buttons on it.
The solution is to make a subclass of UICollectionViewCell and put your set-up code there.
Upvotes: 1