自定义UICollectionViewCell类中的按钮不起作用

问题描述

您好,我正在开发一个路线查找器应用程序,当用户搜索特定位置时,该应用程序内部将在地图上和UICollectionView中提供位置数,其中包含所找到位置列表的简短说明和“转到“ UIButton 显示方向。但是,尽管按钮显示在单元格上并且是可触摸的,这意味着isUserInteractionEnabled为true,但按钮并未触发动作。控制台上未显示“已按下”。 (注意:屏幕截图仅供演示。)

在MapViewController中声明UICollectionView。

let collectionViewOflistofPlaces:UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        let cv = UICollectionView(frame: .zero,collectionViewLayout: layout)
        cv.translatesAutoresizingMaskIntoConstraints = false
        cv.register(CustomCell.self,forCellWithReuseIdentifier: "cell")
        return cv
    }()

在MapViewController的viewDidLoad函数添加了这些行。

collectionViewOflistofPlaces.reloadData()
collectionViewOflistofPlaces.delegate = self

在MapViewController的扩展中,添加了以下几行功能

func setupCollectionViewOflistofPlaces(){
        hideListViewButton.translatesAutoresizingMaskIntoConstraints = false
        hideListViewButton.isUserInteractionEnabled = true
        collectionViewOflistofPlaces.backgroundColor = UIColor.white.withAlphaComponent(0)
        collectionViewOflistofPlaces.topAnchor.constraint(equalTo: listContentView.topAnchor,constant: 0).isActive = true
        collectionViewOflistofPlaces.leadingAnchor.constraint(equalTo: listContentView.leadingAnchor,constant: 10).isActive = true
        collectionViewOflistofPlaces.trailingAnchor.constraint(equalTo: listContentView.trailingAnchor,constant: -10).isActive = true
        collectionViewOflistofPlaces.heightAnchor.constraint(equalToConstant: view.frame.height/5).isActive = true  // ?
    }
    func collectionView(_ collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,sizeforItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: collectionViewOflistofPlaces.frame.height/0.8,height: collectionViewOflistofPlaces.frame.height/1.2)
    }
    
    func collectionView(_ collectionView: UICollectionView,numberOfItemsInSection section: Int) -> Int {
        return landmarks.count
    }

    func collectionView(_ collectionView: UICollectionView,cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionViewOflistofPlaces.dequeueReusableCell(withReuseIdentifier: "cell",for: indexPath) as! CustomCell
        let cellData = self.landmarks[indexPath.item]
        cell.backgroundColor = Colors.violet3
        cell.setData(dataa: cellData) //????????
        cell.delegate = self
        return cell
    }

自定义类别:

import Foundation
import UIKit

protocol CustomCellDelegate {
    func didPrintNameOfPlace(placeName: String)
}

class CustomCell: UICollectionViewCell {
    
//    var data: Landmark? {
//        didSet {
//            guard let data = data else { return }
//
//        }
//    }
    let directButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("Go",for: .normal)
        button.titleLabel?.font = .systemFont(ofSize: 18)
        button.addTarget(
            self,action: #selector(directButtonpressed),for: UIControl.Event.touchUpInside)
        button.backgroundColor = .white
        return button
    }()
    
    var data: Landmark?
    var delegate: CustomCellDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: .zero)
        
        setUpDirectButton()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    func setData(dataa: Landmark){
        data = dataa
        
    }
    
    func setUpDirectButton(){
        contentView.addSubview(directButton)
        directButton.translatesAutoresizingMaskIntoConstraints = false
        directButton.isUserInteractionEnabled = true
        directButton.topAnchor.constraint(equalTo: contentView.topAnchor,constant: 0).isActive = true
        directButton.rightAnchor.constraint(equalTo: contentView.rightAnchor,constant:  0).isActive = true
        directButton.widthAnchor.constraint(equalToConstant: 50).isActive = true
        directButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
        directButton.frame.size.width = 50
        directButton.frame.size.height = 50
    }
    
    @objc func directButtonpressed(sender: UIButton!) {
//        delegate?.didPrintNameOfPlace(placeName: data!.nameOfPlace)
        print("pressed")
        
    }
}
```[Screen shot link][1]


  [1]: https://i.stack.imgur.com/azHSd.jpg

解决方法

剪切此行:

    button.addTarget(
        self,action: #selector(directButtonPressed),for: UIControl.Event.touchUpInside)

...并将其粘贴到setupDirectButton中。您的按钮将开始工作。

,

用惰性标记您的按钮初始化

private lazy var directButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("Go",for: .normal)
        button.titleLabel?.font = .systemFont(ofSize: 18)
        button.addTarget(
            self,for: UIControl.Event.touchUpInside)
        button.backgroundColor = .white
        return button
    }()