简体   繁体   中英

AddTarget on UIButton not firing

I have a UICollectionViewDataSource defined as follows.

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

}

I'm trying to assign a target for my actionButton , however nothing happens when I click it. I made sure to enable isUserInteractionEnabled for the cell and the actionButton .

EDIT:

MyDataSource is used here in my UIView definition:

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

and finally:

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

Here isUserInteractionEnabled

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

Should be true or remove it as by default it's true

collectionView.isUserInteractionEnabled = true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM