Swift 2 无代表

Swift 2 Nil Delegate

所以我想创建一个 IOS 应用程序来生成一组学生,将他们添加到课程中,然后向学生展示。我可以在 table 视图中的列表中显示学生,但现在我想让用户触摸学生的姓名,然后转到包含该学生信息(姓名最高年级等)的页面。学生 class 完美无缺,课程有效,我唯一的问题是我无法让学生从一个视图转到另一个视图。

这是我目前的情况:

//
//  DataTableViewController.swift
//  assignment8
//

import Foundation
import UIKit


class DataTableViewController: UITableViewController {

  var delegate:StudentSelectionDelegate! = nil
  var students = [Student]();
  var course = Course();

  // MARK: - UITableViewDataSource

  override func viewDidLoad() {
    super.viewDidLoad()

    tableView.delegate = self
    tableView.dataSource = self

  }

  func didSelectStudent(controller:UITableViewController, student:Student!) {

    controller.navigationController?.popViewControllerAnimated(true)

  }

  override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    self.course = courseStorage.getCourse();
    self.students = course.getArrayOfStudentSortedByLastName();
    return course.count;
  }


  override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let row = indexPath.row
    let currentStudent = students[row];
    if (delegate != nil) {
      delegate.didSelectStudent(self,student:currentStudent)
    }
    else {
      print ("delegate is nil :(");
    }
    tableView.deselectRowAtIndexPath(indexPath, animated: true)
  }

  override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("studentCell", forIndexPath: indexPath)

    cell.textLabel?.text = students[indexPath.row].lastName + ", " +
      students[indexPath.row].firstName;
    return cell
  }

  override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    print("ping");
    if segue.identifier == "studentSegue" {
      let nextScene =  segue.destinationViewController as! studentViewController
      // Pass the selected object to the new view controller.
      if let indexPath = self.tableView.indexPathForSelectedRow {
        let selectedStudent = students[indexPath.row]
        print (selectedStudent.firstName);
        nextScene.student = selectedStudent;
      }
    }
  }
}

//
//  DataViewController.swift
//  assignment8
//

import UIKit



class DataViewController: UIViewController {

  @IBOutlet weak var dataLabel: UILabel!
  var dataObject: String = ""
  let tableData = ["One","Two","Three"];



  override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
  }

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

  override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    self.dataLabel!.text = dataObject
  }

  func tableView(tableView: UITableView!, numberOfRowsInSection section: Int)
    -> Int {
    return self.tableData.count;
  }
}

//
//  studentViewController.swift
//  assignment8
//

import UIKit

protocol StudentSelectionDelegate {
  func didSelectStudent(controller: UITableViewController, student:Student)
}

class studentViewController: UIViewController {

  var delegate = StudentSelectionDelegate.self;

  var name = String();
  var student = Student();


  @IBOutlet weak var StudentName: UILabel!
  override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
  }

  func didSelectStudent(controller:UITableViewController, student:Student!) {
    student.description;
    print ("pong")
    StudentName.text = student.firstName + " " + student.lastName;

    controller.navigationController?.popViewControllerAnimated(true);
  }

  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }
  //  override func viewWillAppear(animated: Bool) {
  //    StudentName.text = name
  //  }

}

这是我到目前为止的故事板。

因此,每当我尝试单击学生时,它都会打印我决定在委托为 nil 时使用的消息。到目前为止,我已经尝试查看关于 SO 的所有其他答案,但是 none 已经解决了我的问题。

为了能够将信息从一个视图控制器发送到另一个视图控制器,您应该使用 segues。根据图像,这似乎就是您正在做的事情。如果你不知道如何使用 segue,你可以在这里找到一个很好的答案:Sending data with Segue with Swift

使用 segues,您将能够设置下一个视图控制器的委托:

protocol MyDelegate {
     func myFunction()
}

class FirstViewController: UIViewController, MyDelegate {

    func myFunction() {
        // do what the function does
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if let secondVC = segue.destinationViewController as? SecondViewController {
            secondVC.delegate = self
        }
    }
}


class SecondViewController: UIViewController {
    var delegate: MyDelegate!
}

在跳转到第二个视图控制器之前(你正在为跳转做准备),你将SecondViewController的委托变量设置为self,因为FirstViewController符合MyDelegate协议,所以它可以在那里使用。现在,在 SecondViewController 中,您可以使用 delegate.myFunction(),它将执行 FirstVC 函数中编写的任何内容,因为 FirstVC 是 SecondVC 的委托。