Swift - Connect Delegate to Custom Xib Cell

a 夏天 提交于 2020-01-15 05:04:02

问题


[SOLVED]

Solution

When created a Xib File , I hadn't deleted the start UIView. Whereas I had to delete this view and after add new CollectionViewCell in this xib.

Reference: IBAction inside UITableViewCell not called in iOS 9


I use this structure so many times.When I write this delegate with using StoryBoard , it works properly but now it's not. Where is my mistake when use the xib files?

print(indexpath) doesn't work!

import UIKit

class SearchVC: UIViewController {

var searchUid:String?
var comingPage:String?
var searchElements = [ProductElement]()

var collection:UICollectionView!

override func viewDidLoad() {
    super.viewDidLoad()

    if comingPage == "ProductVC" {
        print(searchUid!)
    }

    let searchView : SearchListView = UIView.fromNib()
    searchView.translatesAutoresizingMaskIntoConstraints = false
    self.view.addSubview(searchView)

    searchView.topAnchor.constraint(equalTo: view.safeTopAnchor, constant: 0).isActive = true
    searchView.bottomAnchor.constraint(equalTo: view.safeBottomAnchor, constant: 0).isActive = true
    searchView.rightAnchor.constraint(equalTo: view.safeRightAnchor, constant: 0).isActive = true
    searchView.leftAnchor.constraint(equalTo: view.safeLeftAnchor, constant: 0).isActive = true
    searchView.backgroundColor = UIColor.white

    collection = searchView.collectionView
    collection.translatesAutoresizingMaskIntoConstraints = false

    collection.delegate = self
    collection.dataSource = self

    collection.register(UINib(nibName: "SearchCollectionCell", bundle: nil), forCellWithReuseIdentifier: "SearchCollectionCell")



    let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    layout.minimumInteritemSpacing = 0
    layout.minimumLineSpacing = 10
    collection.collectionViewLayout = layout

    GetElements().search(keywords: ["\(searchUid!)"], contentTypes: ["contenttype_article"]) { (elements) in
        self.searchElements = elements
        self.collection.reloadData()
    }

}

}

extension SearchVC: UICollectionViewDelegate, UICollectionViewDataSource , UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return searchElements.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    var cell: SearchCollectionCell! = collectionView.dequeueReusableCell(withReuseIdentifier: "SearchCollectionCell", for: indexPath) as? SearchCollectionCell

    if cell == nil {
        collectionView.register(UINib(nibName: "SearchCollectionCell", bundle: nil), forCellWithReuseIdentifier: "SearchCollectionCell")
        cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SearchCollectionCell", for: indexPath) as? SearchCollectionCell

    }



    let url = URL(string: "\(String(describing: Config.fileServiceWFileUid!))\(String(describing: searchElements[indexPath.row].oneImage!))")
    cell.searchImage.kf.setImage(with: url)

    cell.productName.text = searchElements[indexPath.row].title
    cell.productCompany.text = searchElements[indexPath.row].description
    cell.delegate = self
    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: collectionView.bounds.size.width / 2 - 5 , height: 175)
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
   // print(indexPath.row)
}

}

extension SearchVC : SearchCollectionCellDelegate {

func searchCellShareButton(sender: SearchCollectionCell) {
    print("AA")
    if let indexpath = collection.indexPath(for: sender) {
        print(indexpath)
    }
}

}

//

protocol SearchCollectionCellDelegate{
    func searchCellShareButton(sender:SearchCollectionCell)
}

class SearchCollectionCell: UICollectionViewCell {

@IBOutlet var searchImage: UIImageView!
@IBOutlet var productName: UILabel!
@IBOutlet var productCompany: UILabel!

var delegate:SearchCollectionCellDelegate?

override func layoutSubviews() {
    searchImage.layer.cornerRadius = 4
}

@IBAction func cellShareButtonAction(_ sender: Any) {

    if delegate != nil {
        delegate?.searchCellShareButton(sender: self)
    }

}
}

[EDIT]

I added didSelectItemAt func. When I try to press "..." button for calling protocol, didSelectItemAt works. I think also this is another mistake.

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    print(indexPath.row)
}

[EDIT 2]

AddTarget Action didn't work. Where is my mistake? Please help me!!!

@IBOutlet var shareButton: UIButton!

weak var delegate:SearchCollectionCellDelegate?

override func awakeFromNib() {
    shareButton.addTarget(self, action: #selector(asd), for: .touchUpInside)
}

@objc func asd(){
    print("asd")
}

回答1:


Used the same code of your's and it is working perfectly fine. Can't figure out why it is not working at your end.

If you are not getting the solution try Closures :

class SecondCollectionViewCell: UICollectionViewCell {

    var callbackOnButton : (()->())?

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    @IBAction func methodButton(_ sender: Any) {
        self.callbackOnButton?()
    }
}

and in cellForRowAtIndex add :

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SecondCollectionViewCell", for: indexPath) as! SecondCollectionViewCell


    cell.callbackOnButton = {
        print("Button Clicked")
    }

    return cell
}



回答2:


try this

in viewDidLoad

override func viewDidLoad() {
    collectionView.register(UINib(nibName: "SearchCollectionCell", bundle: nil), forCellWithReuseIdentifier: "SearchCollectionCell")
}

in your cell class

protocol SearchCollectionCellDelegate:class{
func searchCellShareButton(sender:SearchCollectionCell)
}

 class SearchCollectionCell: UICollectionViewCell {

 @IBOutlet var searchImage: UIImageView!
 @IBOutlet var productName: UILabel!
 @IBOutlet var productCompany: UILabel!

 weak var delegate:SearchCollectionCellDelegate?

override func layoutSubviews() {
searchImage.layer.cornerRadius = 4
}

@IBAction func cellShareButtonAction(_ sender: Any) {

delegate?.searchCellShareButton(sender: self)

}
}

now go to your controller conform protocol

class yourViewController:UIVIewController, SearchCollectionCellDelegate{
 }

in you data source method

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
 guard let cell: SearchCollectionCell! = 
collectionView.dequeueReusableCell(withReuseIdentifier: 
"SearchCollectionCell", 
 for: indexPath) as? SearchCollectionCell else{return UICollectionViewCell() }

cell.delegate = self
return cell
 }



回答3:


Have you registered CollectionViewCell Class with proper identifier in your view controller... if not try to register it in viewDidLoad Method.



来源:https://stackoverflow.com/questions/51239746/swift-connect-delegate-to-custom-xib-cell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!