【问题标题】:AddTarget on UIButton not firingUIButton 上的 AddTarget 未触发
【发布时间】:2019-09-04 05:31:54
【问题描述】:

我有一个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
    }
}

【问题讨论】:

  • 展示你如何使用这个MyDataSource类。您是否验证了对addTarget 的调用实际上已接通?
  • @rmaddy 我做了 - 用断点测试了它 - 另请参阅我对 Sh_Khan 的回答的评论

标签: ios swift uicollectionview uibutton uicollectionviewcell


【解决方案1】:

这里isUserInteractionEnabled

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

应该是true 或将其删除,默认为true

collectionView.isUserInteractionEnabled = true

【讨论】:

  • 所以目前在我定义UiCollectionView的更高级别视图中我有let dataSource = MyDataSource() collectionView.dataSource = dataSource
  • 这个代码在viewDidLoad ??如果是这样,将数据源行作为 var
  • 不是 - 它位于定义所有视图的文件的顶部。
  • 你能分享所有相关的代码吗?确定if table.type == "book" { 命中??
  • MyViewController 的建议更改不正确。 1) UIViewController 已经有一个view 属性。 2)原来的view属性已经是强引用了。
猜你喜欢
  • 2011-06-21
  • 1970-01-01
  • 1970-01-01
  • 2018-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多