i am scrolling at left and right side in collectionView by click button horizontally, it works well, but i do not know how to hide button when is no more item in a side of collectionView. the previewButton will hide when no more item in left side and the next button will hide when no more item in right side. here is code of left and right button
let arrow_leftBtn: UIButton = {
let btn = UIButton()
btn.setImage(UIImage(named: "arrow_left"), for: .normal)
btn.addTarget(self, action: #selector(arrowLeftBtnClick), for: .touchUpInside)
return btn
}()
func arrowLeftBtnClick() {
let collectionBounds = self.collectionView?.bounds
let contentOffset = CGFloat(floor((self.collectionView?.contentOffset.x)! - (collectionBounds?.size.width)!))
self.moveToFrame(contentOffset: contentOffset)
}
let arrow_rightBtn: UIButton = {
let btn = UIButton()
btn.setImage(UIImage(named: "arrow_right"), for: .normal)
btn.addTarget(self, action: #selector(arrowRightBtnClick), for: .touchUpInside)
return btn
}()
func arrowRightBtnClick() {
let collectionBounds = self.collectionView?.bounds
let contentOffset = CGFloat(floor((self.collectionView?.contentOffset.x)! + (collectionBounds?.size.width)!))
self.moveToFrame(contentOffset: contentOffset)
}
func moveToFrame(contentOffset : CGFloat) {
let frame: CGRect = CGRect(x : contentOffset ,y : self.collectionView!.contentOffset.y ,width : self.collectionView!.frame.width,height : self.collectionView!.frame.height)
self.collectionView?.scrollRectToVisible(frame, animated: true)
}
func setupLeftAndRightArrow() {
view.addSubview(arrow_leftBtn)
view.addSubview(arrow_rightBtn)
view.addConstraintsWithFormat("H:|-20-[v0(20)]", views: arrow_leftBtn)
view.addConstraintsWithFormat("V:|-180-[v0(20)]|", views: arrow_leftBtn)
view.addConstraintsWithFormat("H:[v0(20)]-30-|", views: arrow_rightBtn)
view.addConstraintsWithFormat("V:|-180-[v0(20)]|", views: arrow_rightBtn)
}
Implement UICollectionViewDelegate
method:
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath)
{
arrow_rightBtn.isHidden = (indexPath.row == collectionView.numberOfItems(inSection: 0) - 1)
arrow_leftBtn.isHidden = (indexPath.row == 0)
}
This will hide the arrow_rightBtn
when last cell is visible and hide arrow_leftBtn
when first cell is visible.