UITableView:在viewDidLoad()

时间:2018-02-18 13:10:14

标签: ios swift uitableview

我正在尝试将数组中的项加载到Swift iOS App中的UITableView中。

ViewController.swift

import UIKit

class ViewController: UIViewController {

    let website = MyWebsite()
    let authenticated = ViewAuthenticated()

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    @IBAction func getData(_ sender: Any) {
        var arrayTEST = self.website.getArray() //["red", "green", "blue"]
        self.authenticated.data = arrayTEST //["red", "green", "blue"]
        let viewAuth = self.storyboard?.instantiateViewController(withIdentifier: "ViewAuthenticated") as! ViewAuthenticated
        self.present(viewAuth, animated: true)
    }

}

ViewAuthenticated.swift

import UIKit

class ViewAuthenticated: UIViewController, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.dataSource = self
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    public var data: [String] = ["123", "456", "789"]

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellReuseIdentifier")!
        let text = data[indexPath.row]
        cell.textLabel?.text = text
        return cell
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }


}

我想要做的是创建一个包含ViewController发送的项目的UITableView。 我认为问题是在ViewAuthenticated中,在ViewController发送新数组([“red”,“green”,“blue”])之前创建了UITableView。 我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

在呈现视图之前,您应该将值数组设置为ViewAuthenticated View的data属性。

@IBAction func getData(_ sender: Any) {
        var arrayTEST = self.website.getArray() //["red", "green", "blue"]
        self.authenticated.data = arrayTEST //["red", "green", "blue"]
        let viewAuth = self.storyboard?.instantiateViewController(withIdentifier: "ViewAuthenticated") as! ViewAuthenticated
        viewAuth.data = self.authenticated.data
        self.present(viewAuth, animated: true)
    }

并删除硬编码数据数组值。将其更改为:

var data: [String] = []

答案 1 :(得分:0)

简单的解决方案,根本不需要authenticated控制器:

<击> let authenticated = ViewAuthenticated()

...

@IBAction func getData(_ sender: Any) {
    let viewAuth = self.storyboard?.instantiateViewController(withIdentifier: "ViewAuthenticated") as! ViewAuthenticated
    viewAuth.data = self.website.getArray() //["red", "green", "blue"]
    self.present(viewAuth, animated: true)
}