自定义 UICollectionViewCell class 中的按钮没有采取行动

Button in custom UICollectionViewCell class does not taking action

您好,我正在开发一个路线查找器应用程序,当用户搜索特定地点时,在应用程序内部,应用程序会在地图和 UICollectionView 中提供地点数量,其中包含找到的地点列表的简短描述和 "Go" UIButton 显示方向。然而,尽管按钮显示在单元格上并且是可触摸的,这意味着 isUserInteractionEnabled 为真,但按钮并未触发操作。 “按下”未显示在控制台上。 (注意:屏幕截图可用于演示目的。)

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
    }

自定义 class:

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,
            action: #selector(directButtonPressed),
            for: UIControl.Event.touchUpInside)
        button.backgroundColor = .white
        return button
    }()