从UICollectionViewCell执行Segue

时间:2018-05-29 23:03:03

标签: ios swift xcode uicollectionview uicollectionviewcell

所以我正在创建一个博客应用程序,并在主页新闻源集合视图(imageCollection,从firebase数据库加载)我有一个按钮。此按钮标题取决于图像的类别。我遇到的问题是在UICollectionViewCell类中执行segue。我使用print语句运行按钮操作,它工作正常。但是当我尝试添加performSegue时,它不会让我。 (使用未解析的标识符'performSegue')

任何提示?谢谢!

P.S。我仍然相当新闻,所以如果我有点无知,我道歉

我的ViewController

import UIKit
import Firebase
import FirebaseDatabase
import SDWebImage

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {



@IBOutlet weak var popImageCollection: UICollectionView!
@IBOutlet weak var imageCollection: UICollectionView!


var customImageFlowLayout = CustomImageFlowLayout()
var popImageFlowLayout = PopImagesFlowLayout()
var images = [BlogInsta]()
var popImageArray = [UIImage]()
var homePageTextArray = [NewsTextModel]()

var dbRef: DatabaseReference!
var dbPopularRef: DatabaseReference!

override func viewDidLoad() {
    super.viewDidLoad()
    dbRef = Database.database().reference().child("images")
    dbPopularRef = Database.database().reference().child("popular")
    loadDB()
    loadImages()
    loadText()
    customImageFlowLayout = CustomImageFlowLayout()
    popImageFlowLayout = PopImagesFlowLayout()

    imageCollection.backgroundColor = .white
    popImageCollection.backgroundColor = .white


    // Do any additional setup after loading the view, typically from a nib.
}
func loadText() {
    dbRef.observe(DataEventType.value, with: { (snapshot) in
        if snapshot.childrenCount > 0 {
            self.homePageTextArray.removeAll()
            for homeText in snapshot.children.allObjects as! [DataSnapshot] {
                let homeTextObject = homeText.value as? [String: AnyObject]
                let titleHome = homeTextObject?["title"]
                let categoryButtonText = homeTextObject?["category"]
                self.imageCollection.reloadData()
                let homeLabels = NewsTextModel(title: titleHome as! String?, buttonText: categoryButtonText as! String?)
                self.homePageTextArray.append(homeLabels)
            }
        }
    })
}
func loadImages() {
    popImageArray.append(UIImage(named: "2")!)
    popImageArray.append(UIImage(named: "3")!)
    popImageArray.append(UIImage(named: "4")!)

    self.popImageCollection.reloadData()
}
func loadDB() {
    dbRef.observe(DataEventType.value, with: { (snapshot) in
        var newImages = [BlogInsta]()
        for BlogInstaSnapshot in snapshot.children {
            let blogInstaObject = BlogInsta(snapshot: BlogInstaSnapshot as! DataSnapshot)
            newImages.append(blogInstaObject)
}
self.images = newImages
self.imageCollection.reloadData()
})

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    if collectionView == self.imageCollection {
       return images.count
    } else {
        return popImageArray.count
    }

}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if collectionView == self.imageCollection {
   let cell = imageCollection.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! ImageCollectionViewCell
    let image = images[indexPath.row]
        let text: NewsTextModel
        text = homePageTextArray[indexPath.row]
        cell.categoryButton.setTitle(text.buttonText, for: .normal)
        cell.newTitleLabel.text = text.title
    cell.imageView.sd_setImage(with: URL(string: image.url), placeholderImage: UIImage(named: "1"))
        return cell
    } else {
       let cellB = popImageCollection.dequeueReusableCell(withReuseIdentifier: "popCell", for: indexPath) as! PopularCollectionViewCell
        let popPhotos = popImageArray[indexPath.row]
        cellB.popularImageView.image = popPhotos
        cellB.popularImageView.frame.size.width = view.frame.size.width
            return cellB
    }

}


}

我的ImageCollectionViewCell.swift

import UIKit
import Foundation

class ImageCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var categoryButton: UIButton!

@IBOutlet weak var newTitleLabel: UILabel!

@IBOutlet weak var imageView: UIImageView!


@IBAction func categoryButtonAction(_ sender: Any) {
    if categoryButton.currentTitle == "Fashion" {
        print("Fashion Button Clicked")
        performSegue(withIdentifier: "homeToFashion", sender: self)
    }

}

override func prepareForReuse() {
    super.prepareForReuse()
    self.imageView.image = nil
    }

}

2 个答案:

答案 0 :(得分:2)

您需要自定义委托。这样做:

protocol MyCellDelegate {
    func cellWasPressed()
}

// Your cell
class ImageCollectionViewCell: UICollectionViewCell {
    var delegate: MyCellDelegate?

    @IBAction func categoryButtonAction(_ sender: Any) {
        if categoryButton.currentTitle == "Fashion" {
            print("Fashion Button Clicked")
            self.delegate?.cellWasPressed()
        }
    }

}

// Your viewcontroller must conform to the delegate
class ViewController: MyCellDelegate {
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if collectionView == self.imageCollection {
        let cell = imageCollection.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! ImageCollectionViewCell

        // set the delegate
        cell.delegate = self
      // ...... rest of your cellForRowAtIndexPath
    }


// Still in your VC, implement the delegate method
    func cellWasPressed() {
       performSegue(withIdentifier: "homeToFashion", sender: self)
    }
}

答案 1 :(得分:0)

您应该使用自己的代理人。已经描述了here

performSegue(withIdentifier:sender:)无法在单元格中工作,因为它是UIViewController metod。

您也可以use of closure