ios - UIButton 上的 AddTarget 未触发

标签 ios swift uicollectionview uibutton uicollectionviewcell

我有一个 UICollectionViewDataSource 定义如下。

class MyDataSource : NSObject, UICollectionViewDataSource {

var tables : [Table]?


...


func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if let cell: TableCVCell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? TableCVCell {
        let row = indexPath.row
        let table = tables![row]
        cell.isUserInteractionEnabled = true
        if table.type == "book" {
            cell.actionButton.table = table
            cell.actionButton.addTarget(self, action: #selector(btnClicked(sender:)), for: .touchUpInside)
        }
        return cell
    }
    return UICollectionViewCell()
}

@objc func btnClicked(sender : ActionButton) {
    print("clicked")
} 

}

我正在尝试为我的 actionButton 分配一个目标,但是当我点击它时没有任何反应。我确保为单元格和 actionButton 启用 isUserInteractionEnabled

编辑:

MyDataSource 在我的 UIView 定义中使用:

class MyView: UIView {

var collectionView : UICollectionView!
    let flowLayout = UICollectionViewFlowLayout()
    let cvDelegate = MYDelegate()
    let dataSource = MyDataSource()

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupCollectionView()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupCollectionView()
    }

func setupCollectionView() {
        flowLayout.scrollDirection = .vertical

        collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight), collectionViewLayout: flowLayout)
        collectionView.delegate = cvDelegate
        collectionView.dataSource = dataSource
        collectionView.isUserInteractionEnabled = false
        collectionView.register(TableCVCell.self, forCellWithReuseIdentifier: "cell")
    }

最后:

MyViewController : UIViewController {
 override func loadView() {
        let view = MyView()
        self.view = view
    }
}

最佳答案

这里是UserInteractionEnabled

collectionView.delegate = cvDelegate
collectionView.dataSource = dataSource 
collectionView.isUserInteractionEnabled = false

应为 true 或将其删除,因为默认情况下为 true

collectionView.isUserInteractionEnabled = true

关于ios - UIButton 上的 AddTarget 未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55668766/

相关文章:

iOS从应用程序内转到设置应用程序

ios - 如何在 Xcode 中配置方案以在归档之前始终运行单元测试?

Swift:正则表达式搜索 for 循环没有进行

ios - 在 UIWebview Swift 中居中嵌入的 youtube 视频

ios - 关于 CollectionViewCell

ios - XCode SVN 清理

ios - ARKit:如何将 UIView 添加到 ARKit 场景?

ios - 自定义布局CollectionView无法滚动

swift - 每个自定义单元格和自定义高度

ios - 如何使用 OpenGL ES 共享组在 iPad 上共享渲染缓冲区以进行屏幕镜像?