从 UICollectionViewCell 调用函数以在 UICollectionView 中使用

Call function from UICollectionViewCell to use in UICollectionView

我有一个创建一堆文本字段的 UICollectionViewCell 和一个查看在单元格中创建的所有文本字段并将它们写入 firebase 的函数 (handleNewJob)。

但是,我想要的是我在 UICollectionView 中创建的按钮,用于从 UICollectionViewCell 调用函数 (handleNewJob)。

这可能吗?我试过在 UICollectionView 中使用该功能,但我似乎无法引用所有 textfields.text?

这是我在 UICollectionViewCell 中的函数(我没有包括所有文本字段生成,因为它很长):

        // HANDLE NEW JOB
        func handleNewJob(){
            let newJobBrand = jobBrand.text!
            let newJobName = jobName.text!
            let newDirectorName = directorName.text!
            let newAgencyName = agencyName.text!
            let newProdCoName = prodCoName.text!
            // WHERE TO PUT IN DATABASE
            let reference = Database.database().reference().child("jobInfo")
            let childRef = reference.childByAutoId()
            // REFERENCING DICTIONARY
            let jobBrandValue = ["jobBrand": newJobBrand]
            let jobNameValue = ["jobName": newJobName]
            let jobDirectorValue = ["directorName": newDirectorName]
            let jobAgencyNameValue = ["agencyName": newAgencyName]
            let jobProdCoValue = ["prodCoName": newProdCoName]
            // WRITE TO DATABASE
            childRef.updateChildValues(jobBrandValue)
            childRef.updateChildValues(jobNameValue)
            childRef.updateChildValues(jobDirectorValue)
            childRef.updateChildValues(jobAgencyNameValue)
            childRef.updateChildValues(jobProdCoValue)
        }

这是我的 UICollectionView 代码 - 我想调用 handleNext 按钮下的函数:

          import UIKit
      import Firebase

      class page_newJobSwipingController : UICollectionViewController, UICollectionViewDelegateFlowLayout, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

          // VARIABLES
          var ref:DatabaseReference?

              // BOTTOM BUTTONS
          private let previousButton: UIButton = {
              let button = UIButton(type: .system)
              button.setTitle("Previous", for: .normal)
              button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14)
              button.setTitleColor(.gray, for: .normal)
              button.addTarget(self, action: #selector(handlePrev), for: .touchUpInside)
              button.translatesAutoresizingMaskIntoConstraints = false
              return button
          }()
          private let nextButton: UIButton = {
              let button = UIButton(type: .system)
              button.setTitle("Next", for: .normal)
              button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14)
              let pinkColour = UIColor(red: 232/255, green: 68/266, blue: 133/255, alpha: 1)
              button.setTitleColor(.mainPink, for: .normal)
              button.translatesAutoresizingMaskIntoConstraints = false
              button.addTarget(self, action: #selector(handleNext), for: .touchUpInside)
              return button
          }()

              // SET UP NEXT AND PREVIOUS BUTTONS TO HAVE A FUNCTION
          @IBAction func handlePrev(sender : UIButton) {
              let prevIndex = max(pageControl.currentPage - 1, 0)
              pageControl.currentPage = prevIndex
              let indexPath = IndexPath(item: prevIndex, section: 0)
              collectionView?.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
          }
          @IBAction func handleNext(sender : UIButton) {
              let nextIndex = pageControl.currentPage + 1
              pageControl.currentPage = nextIndex
              if nextIndex == 1 {
                  print ("move to page 2")
              } else {
                  print ("send alert message")
                  newJobCellGeneral.handleNewJob()
                  storyboardAlert()
              }

              let indexPath = IndexPath(item: 1, section: 0)
              collectionView?.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
          }

          // HANDLE UPLOAD STORYBOARD OPTIONS
          @IBAction func storyboardAlert() {

              let imagePickerController = UIImagePickerController()
              imagePickerController.delegate = self
              // ACTION SHEET FOR ADDING NEW ATTACHMENT
              let alert = UIAlertController(title: "Job Created", message: "Do you want to upload storyboard cells now?", preferredStyle: .actionSheet)
              alert.addAction(UIAlertAction(title: "Now", style: .default, handler: { (action:UIAlertAction) in
                  let storyboardUpload = page_newJobStoryboardUpload()
                  self.show(storyboardUpload, sender: self)
              }))
              alert.addAction(UIAlertAction(title: "Later", style: .default, handler: { (action:UIAlertAction) in
                  let jobList = page_jobList()
                  self.show(jobList, sender: self)
              }))
              alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
              self.present(alert, animated: true, completion: nil)
          }

              // PAGE CONTROL
          private let pageControl: UIPageControl = {
              let pc = UIPageControl()
              pc.numberOfPages = 2
              pc.currentPageIndicatorTintColor = .mainPink
              pc.pageIndicatorTintColor = UIColor(red: 249/255, green: 207/266, blue: 224/255, alpha: 1)
              return pc
          }()
          override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
              let x = targetContentOffset.pointee.x
              pageControl.currentPage = Int(x / view.frame.width)
          }
              // CONSTRAINTS OF BOTTOM CONTROLS
          fileprivate func setupBottomControls(){
              let bottomControlsStackView = UIStackView(arrangedSubviews: [previousButton, pageControl, nextButton])

              bottomControlsStackView.translatesAutoresizingMaskIntoConstraints = false
              bottomControlsStackView.distribution = .fillEqually
              view.addSubview(bottomControlsStackView)

              NSLayoutConstraint.activate([
                  bottomControlsStackView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
                  bottomControlsStackView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
                  bottomControlsStackView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
                  bottomControlsStackView.heightAnchor.constraint(equalToConstant: 50)
                  ])
          }

          // SUPER VIEW DID LOAD
          override func viewDidLoad() {
              super.viewDidLoad()

              collectionView?.backgroundColor = .white
              collectionView?.register(newJobCellGeneral.self, forCellWithReuseIdentifier: "newJobCellGeneral")
              collectionView?.register(newJobCellTechnical.self, forCellWithReuseIdentifier: "newJobCellTechnical")
              collectionView?.isPagingEnabled = true

              setupBottomControls()

          }
          func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
              return 0
          }
          override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
              return 2
          }
          override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

              if indexPath.item == 0 {

                  let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "newJobCellGeneral", for: indexPath) as! newJobCellGeneral
                  navigationItem.title = "General Info"
                  return cell
              } else {
                  let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "newJobCellTechnical", for: indexPath) as! newJobCellTechnical
                  navigationItem.title = "Technical Specs"
                  return cell
              }
          }
          func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
              return CGSize(width: view.frame.width, height: view.frame.height)
          }
      }

流程是相反的,但是,最简单的方法是通过通知 在你 collection 查看

将其放入您的 collectionView button pressed 方法中

NotificationCenter.default.post(name: Notification.Name("handleNewJob"), object: nil)

在你中添加观察者collection view cell (init or awakeFromNib depends)

NotificationCenter.default.addObserver(self, selector: #selector(handleNewJob, name: NSNotification.Name(rawValue: "handleNewJob"), object: nil)

通知中心是一种解决方案,但更简单的方法是能够直接从单元格调用集合视图控制器上的函数。

为此,您需要能够引用您的父视图控制器。所以添加这个 UIView 扩展:

创建一个名为 UIView.swift 的 swift 文件并粘贴:

import UIKit
extension UIView {
    var parentViewController: UIViewController? {
        var parentResponder: UIResponder? = self
        while parentResponder != nil {
            parentResponder = parentResponder!.next
            if parentResponder is UIViewController {
                return parentResponder as! UIViewController!
            }
        }
        return nil
    }
} 

然后从您的单元格中,例如单击按钮时:

@IBAction func someButtonAction(sender : UIButton) {
    let parent = self.parentViewController as! page_newJobSwipingController

    parent.whateverFunction()
}