在 collectionView 中完成移动后无法隐藏按钮

unable to hide button after completing moving in collectionView

我通过水平单击按钮在 collectionView 的左侧和右侧滚动,效果很好,但我不知道如何在 collectionView 的一侧没有更多项目时隐藏按钮。当左侧没有更多项目时,预览按钮将隐藏,当右侧没有更多项目时,下一个按钮将隐藏。这是左右按钮的代码

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)
}

您可以使用 collectionView 委托方法检测第一个最后一个单元格

override func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
    if indexPath.row == dataSource.count - 1 {
        // Last cell is visible
        leftBtn.isHidden = false
        rightBtn.isHidden =true
    } else if indexPath.row == 0 {
        // First cell is visible
        leftBtn.isHidden = true
        rightBtn.isHidden = false
    } else {
        //for others cells
        leftBtn.isHidden = false
        rightBtn.isHidden =false

    }
}

实施UICollectionViewDelegate方法:

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)
}

这将在最后一个单元格可见时隐藏 arrow_rightBtn 并在第一个单元格可见时隐藏 arrow_leftBtn