簡體   English   中英

UICollectionCellView 委托沒有被觸發

[英]UICollectionCellView delegate not being fired

我創建的 UICollectionView 不想觸發自定義單元委托。

單元格正在顯示,並且測試按鈕接受按下。

我已經調試了代碼,並且 cell.delegate 被分配了自我。

我在谷歌上對此進行了研究,但一無所獲。 我認為我的代碼沒問題,但我一定遺漏了什么?

我真的很感激任何幫助。

//HomeControllerDelegateTesting.swift

import UIKit

class HomeControllerDelegateTesting: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, PostCellOptionsDelegate {

    var collectionView: UICollectionView! = nil

    override func viewDidLoad() {
        super.viewDidLoad()

        self.collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: self.createLayout())
        self.collectionView.register(PostCell.self, forCellWithReuseIdentifier: PostCell.reuseIdentifier)
        self.collectionView.backgroundColor = .systemBackground
        self.view.addSubview(collectionView)
        self.collectionView.dataSource = self
        self.collectionView.delegate = self

    }

    private func createLayout() -> UICollectionViewLayout {
        let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0),
                                             heightDimension: .fractionalHeight(1.0))
        let item = NSCollectionLayoutItem(layoutSize: itemSize)

        let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0),
                                               heightDimension: .estimated(300))
        let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize,
                                                         subitems: [item])
        let section = NSCollectionLayoutSection(group: group)

        let layout = UICollectionViewCompositionalLayout(section: section)
        return layout
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: PostCell.reuseIdentifier, for: indexPath) as? PostCell else { fatalError("Cannot create cell") }

        cell.postTextLabel.text = "Test"
        cell.delegate = self
        //Test to eliminiate the button accepts events
        //cell.optionsButtons.addTarget(self, action: #selector(test), for: .touchUpInside)
        return cell
    }

    @objc func handlePostOptions(cell: PostCell) {
        print("123")
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 3
    }
}

//  PostCell.swift


import UIKit

protocol PostCellOptionsDelegate: class {
    func handlePostOptions(cell: PostCell)
}


class PostCell: UICollectionViewCell {
    static let reuseIdentifier = "list-cell-reuse-identifier"

    var delegate: PostCellOptionsDelegate?

    let usernameLabel: UILabel = {
        let label = UILabel()
        label.text = "Username"
        label.font = .boldSystemFont(ofSize: 15)
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    let postImageView: UIImageView = {
        let control = UIImageView()
        control.translatesAutoresizingMaskIntoConstraints = false
        control.contentMode = .scaleAspectFill
        control.clipsToBounds = true
        return control
    }()

    let postTextLabel: UILabel = {
        let label = UILabel()
        label.text = "Post text spanning multiple lines"
        label.font = .systemFont(ofSize: 15)
        label.numberOfLines = 0
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()


//    private let optionsButtons: UIButton = {
//        let control = UIButton.systemButton(with: #imageLiteral(resourceName: "post_options"), target: self, action: #selector(handleOptions))
//        control.translatesAutoresizingMaskIntoConstraints = false
//        return control
//    }()

    let optionsButtons: UIButton = {
        let control = UIButton(type: .system)
        control.setTitle("Test", for: .normal)
        control.addTarget(self, action: #selector(handleOptions), for: .touchUpInside)
        control.translatesAutoresizingMaskIntoConstraints = false
        return control
    }()

    @objc fileprivate func handleOptions() {
        print("Handle options button")
        delegate?.handlePostOptions(cell: self)
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupComponents()

    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setupComponents() {

        self.optionsButtons.heightAnchor.constraint(equalToConstant: 50).isActive = true

        let labelStack = UIStackView(arrangedSubviews: [optionsButtons])
        labelStack.translatesAutoresizingMaskIntoConstraints = false
        labelStack.axis = .horizontal
        labelStack.alignment = .fill
        labelStack.distribution = .fill
        labelStack.isLayoutMarginsRelativeArrangement = true
        labelStack.layoutMargins.left = 16
        labelStack.layoutMargins.right = 16
        labelStack.layoutMargins.top = 16
        labelStack.layoutMargins.bottom = 16

        let postTextLabelStack = UIStackView(arrangedSubviews: [postTextLabel])

        postTextLabelStack.translatesAutoresizingMaskIntoConstraints = false
        postTextLabelStack.axis = .vertical
        postTextLabelStack.alignment = .fill
        postTextLabelStack.distribution = .fill
        postTextLabelStack.isLayoutMarginsRelativeArrangement = true
        postTextLabelStack.layoutMargins.left = 16
        postTextLabelStack.layoutMargins.right = 16
        postTextLabelStack.layoutMargins.top = 16
        postTextLabelStack.layoutMargins.bottom = 16

        let stack = UIStackView(arrangedSubviews: [labelStack, postImageView, postTextLabelStack])
        stack.translatesAutoresizingMaskIntoConstraints = false
        stack.axis = .vertical
        stack.alignment = .fill
        stack.distribution = .fill
        stack.backgroundColor = .blue

        self.addSubview(stack)

        //postImageView.heightAnchor.constraint(equalTo: postImageView.widthAnchor).isActive = true

        stack.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
        stack.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
        stack.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true
        stack.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true

    }
}

將您的按鈕聲明更改為:

// make this a lazy var
lazy var optionsButtons: UIButton = {
    let control = UIButton(type: .system)
    control.setTitle("Test", for: .normal)
    // add self. to the selector
    control.addTarget(self, action: #selector(self.handleOptions), for: .touchUpInside)
    control.translatesAutoresizingMaskIntoConstraints = false
    return control
}()

問題是,當創建optionsButtons時, self仍未初始化。 因此,您需要使按鈕lazy var以便在調用UICollectionViewCell並初始化optionsButtons時延遲加載。 self初始化之前添加目標不起作用。

要解決您的問題,請將您的optionsButtons聲明修改為lazy var ,如下所示:

lazy var optionsButtons: UIButton = {

或者

在 UICollectionViewCell 初始化后添加目標,如下所示:

override init(frame: CGRect) {
    super.init(frame: frame)
    optionsButtons.addTarget(self, action: #selector(handleOptions), for: .touchUpInside)
    setupComponents()
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM