将数据插入swift类型的数组中

时间:2017-11-19 03:22:32

标签: ios arrays swift4 xcode9

如何将textfield文本的值插入类型类数组?

基本上,我有两个视图控制器,一个显示使用以下类创建的项目和代码列表

class Courses {

    var courseName : String
    var courseCode : Int

    init(courseName : String, courseCode : Int){
        self.courseName = courseName
        self.courseCode = courseCode
    }
}

//从该类创建数组

var courses : [Courses] = [Courses(courseName: "Unix Linux", courseCode: 101),
                               Courses(courseName: "ASP.Net", courseCode: 202),
                               Courses(courseName: "CISCO", courseCode: 203),
                               Courses(courseName: "Photoshop Editing", courseCode: 306)
                               ]

第二个视图控制器有两个文本字段,允许有人向现有数组添加新课程。如何实现这一点并使用来自不同视图控制器的新项重新加载表视图

我在第二个视图controller.swift文件中添加了var课程:[Courses] = []。不知道还能做什么。 我试过这样的事情

@IBAction func addCourseButton(_ sender: Any) {
        if courseName.text != "" {

            let courseCodeString = Int(courseCode.text!)
            let item = Courses(courseName: "\(courseName.text)", courseCode: courseCodeString!)

            courses.append(item)

            for i in courses {
                print(i.courseName)
            }
        }
    }

enter image description here enter image description here

1 个答案:

答案 0 :(得分:0)

您的问题有两种可能的解决方案。

  1. 使用协议
  2. 使用通知观察员
  3. 在第一种情况下,

    在第二个ViewController.swift中添加协议,就在类定义

    之上
    protocol UpdateCourseAfterAddProtocol:class {
    
        func classListUpdated(with course: Courses)
    
    
    }
    
    
    
    
    
    class SecondViewController:UIViewController  {
    
        weak var dele:UpdateCourseAfterAddProtocol? = nil
    
    
    
    @IBAction func addCourseButton(_ sender: Any) {
            if courseName.text != "" {
    
                let courseCodeString = Int(courseCode.text!)
                let item = Courses(courseName: "\(courseName.text)", courseCode: courseCodeString!)
    
              dele?.classListUpdated(with: item)
            }
        }
    
    }
    

    将Main.storyboard中的Segue名称添加到“firstToSecond”或任何名称 在第一个View Controller中,表View Exists(假设名称是FirstViewController)

        class FirstViewController {
    
    
           // Bar button Action
           @IBAction func addCoursePressed(_ send:UIBarButton) {
    
            self.performsegue(with:"firstToSecond")
          }
         override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    
        if segue.identifier == "firstToSecond" {
    
            let toViewController = segue.destination as! SecondViewController
    
            toViewController.dele = self
    
    
    
        }
      }
    }
    extension FirstViewController: UpdateCourseAfterAddProtocol {
    
        func classListUpdated(with course: Courses) {
    
            self.courses.append(course)
            self.tableView.reloadData()
         }
    
    
    
    }