【问题标题】:Control collectionView Scrolling from within collectionView Cell控制 collectionView 从 collectionView Cell 内滚动
【发布时间】:2017-06-03 00:56:05
【问题描述】:

是否可以通过在集合视图 Cell .swift 文件中编写代码来阻止我的集合视图滚动。我希望能够在用户点击单元格中的按钮时停止滚动,然后在再次按下按钮时允许滚动。

【问题讨论】:

    标签: ios swift uicollectionview


    【解决方案1】:

    为您的单元创建自定义委托

    protocol CustomCellDelegate: class {
        func cellDidSetScrolling(enabled: Bool)
    }
    
    class CustomCell: UICollectionViewCell {
    
        var delegate: CustomCellDelegate?
    
        // ....
    }
    

    将委托分配给cellForItem中的单元格

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        // dequeue cell and assign delegate
        var cell: CustomCell?
       cell.delegate = self
       return cell
    }
    

    在按钮操作上调用单元委托。使用button.tag 确定enabled 的值

    func buttonAction() {
        button.tag = button.tag == 0 ? 1 : 0 // toggle value
        delegate?.cellDidSetScrolling(enabled: button.tag == 1)
    }
    

    ViewController中实现委托

    class ViewController: UIViewController, CustomCellDelegate {
    
        func cellDidSetScrolling(enabled: Bool) {
            collectionView.isScrollEnabled = enabled
        }
    }
    

    编码愉快!

    【讨论】:

    • 太棒了。如果 button.tag 等于 1 是什么意思?
    • 代码将切换 isScrollEnabled 的值。也就是说,如果启用滚动,则点击按钮将禁用它,反之亦然。
    • 我在问一些不同的问题。如果我错了,请纠正我:默认情况下,按钮标签设置为0(我的意思是你不需要给它一个初始值。对)......所以一旦点击它,你就将它设置为1并基于此做出isScrollEnabled 的决定...您基本上是在滥用标签属性来进行此操作...
    • 没错。或者,您可以简单地添加一个变量来存储按钮的状态(:
    • 我和 jože 在一起。我不明白为什么这是滥用标签。随心所欲地使用标签。毕竟你是唯一一个改变它的人。
    猜你喜欢
    • 1970-01-01
    • 2017-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-03
    • 2021-01-23
    • 2017-01-22
    相关资源
    最近更新 更多