Swift-将代表连接到自定义Xib单元

时间:2018-07-09 07:00:11

标签: swift xcode xib swift-protocols

[已解决]

解决方案

创建Xib文件时,我没有删除启动UIView。而我不得不删除此视图,然后在此xib中添加新的CollectionViewCell。

参考:IBAction inside UITableViewCell not called in iOS 9


我多次使用此结构,当我使用StoryBoard编写此委托时,它可以正常工作,但现在不行了。使用xib文件时我的错误在哪里?

打印(索引路径)不起作用!

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

}
}

enter image description here [编辑]

我添加了didSelectItemAt函数。当我尝试按“ ...”按钮以调用协议时,didSelectItemAt起作用。我认为这也是另一个错误。

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

[编辑2]

AddTarget操作不起作用。我的错误在哪里?请帮帮我!

@IBOutlet var shareButton: UIButton!

weak var delegate:SearchCollectionCellDelegate?

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

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

3 个答案:

答案 0 :(得分:1)

使用了与您相同的代码,它工作得很好。无法弄清楚为什么它在您的末端无法正常工作。

如果您没有解决方案,请尝试Closures

class SecondCollectionViewCell: UICollectionViewCell {

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

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

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

,然后在cellForRowAtIndex中添加:

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
}

答案 1 :(得分:0)

尝试

在viewDidLoad

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

在您的单元格班级

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)

}
}

现在转到您的控制器遵循协议

class yourViewController:UIVIewController, SearchCollectionCellDelegate{
 }

在您的数据源方法中

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
 }

答案 2 :(得分:0)

您是否在视图控制器中注册了具有正确标识符的CollectionViewCell类... 如果没有,请尝试在viewDidLoad方法中注册它。