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

Swift 从UICollectionViewCell调用函数以在UICollectionView中使用,swift,uicollectionview,uicollectionviewcell,Swift,Uicollectionview,Uicollectionviewcell,我有一个UICollectionViewCell,它创建了一组文本字段,还有一个函数handleNewJob,它查看在单元格中创建的所有文本字段,并将它们写入firebase 但是,我想要的是我在UICollectionView中创建的按钮从UICollectionViewCell调用函数handleNewJob 这可能吗?我已尝试在UICollectionView中使用该函数,但似乎无法引用所有文本字段。text 以下是我在UICollectionViewCell中的函数,我没有包含所有文本字

我有一个UICollectionViewCell,它创建了一组文本字段,还有一个函数handleNewJob,它查看在单元格中创建的所有文本字段,并将它们写入firebase

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

这可能吗?我已尝试在UICollectionView中使用该函数,但似乎无法引用所有文本字段。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)
          }
      }

流程是反向的,但是是的,最简单的方法是通过通知 在您的集合视图中

将其放入collectionView按钮按下的方法中

NotificationCenter.default.post(name: Notification.Name("handleNewJob"), object: nil)
在集合视图单元格init或awakeFromNib中添加观察者取决于

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

流程是反向的,但是是的,最简单的方法是通过通知 在您的集合视图中

将其放入collectionView按钮按下的方法中

NotificationCenter.default.post(name: Notification.Name("handleNewJob"), object: nil)
在集合视图单元格init或awakeFromNib中添加观察者取决于

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

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

为此,您需要能够引用父视图控制器。因此,添加此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()
}

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

为此,您需要能够引用父视图控制器。因此,添加此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()
}

一旦我添加了这两行,我应该在handleNext按钮中输入什么来调用该函数?我只想在按下按钮时调用该函数。我现在有newJobCellGeneral.handleNewJob,我得到的错误实例成员“handleNewJob”不能用于类型“newJobCellGeneral”;你的意思是使用这种类型的值吗?这段代码起作用了-但是我没有将第一行放入viewDidLoad,而是将它放入我的button函数中,这样它只有在点击时才会被调用。谢谢你的帮助。一旦我添加了这两行,我应该在handleNext按钮中添加什么来调用该函数?我只想在按下按钮时调用该函数。我现在有newJobCellGeneral.handleNewJob,我得到的错误实例成员“handleNewJob”不能用于类型“newJobCellGeneral”;你的意思是使用这种类型的值吗?这段代码起作用了-但是我没有将第一行放入viewDidLoad,而是将它放入我的button函数中,这样它只有在点击时才会被调用。感谢您的帮助。我已将第一块代码放在UICollectionViewController的底部,将第二块代码放在函数上方的单元格中。然而,我得到了这些错误的细胞。对于类型为“newJobCellGeneral->->newJobCellGeneral”的let行值,没有成员“parent”,第二行需要声明。请创建一个名为UIViewExtension的新swift文件,但此名称并不重要,请将第一段代码放入其中。然后在你的单元格内,在你想调用父函数的地方,使用第二个代码块。当我将第二个文本块复制到我的UIViewCollectionViewCell类名:newJobCellGeneral时,我得到了类型为“newJobCellGeneral”的错误值,它没有成员“parent”。不要担心错误,我已经修复了它。感谢您的帮助-我发现只要代码位于正确的位置,@zheck answer就可以轻松工作。因为您可能缺少一行let parent=self.parentViewController as!page_newJobSwipingController在同一函数中我已将第一块代码放在UICollectionViewController的底部,将第二块代码放在函数上方的单元格中。然而,我得到了这些错误的细胞。对于类型为“newJobCellGeneral->->newJobCellGeneral”的let行值,没有成员“parent”,第二行需要声明。请创建一个名为UIViewExtension的新swift文件,但此名称并不重要,请将第一段代码放入其中。然后在你的单元格内,在你想调用父函数的地方,使用第二个代码块。当我将第二个文本块复制到我的UIViewCollectionViewCell类名:newJobCellGeneral时,我得到了类型为“newJobCellGeneral”的错误值,它没有成员“parent”。不要担心
我已经修好了。感谢您的帮助-我发现只要代码位于正确的位置,@zheck answer就可以轻松工作。因为您可能缺少一行let parent=self.parentViewController as!page_同一功能中的newJobSwipingController