首页 > 解决方案 > 试图将数组移动到表格视图

问题描述

我正在尝试将目标从数组移动到 tableview 并且无法完成此任务。

这是我的代码。

import UIKit

class GoalsViewController: UIViewController {

@IBOutlet weak var goalTableView: UITableView!
@IBOutlet weak var goalCategoryLabel: UILabel!

var valueToPass = ""
var goals: [String] = []
let theEmptyModel: [String] = ["No data in this section."]

var firstGoals = ["run", "walk", "jog"]
var secondGoals = ["sleep", "rest"]

var goalCategoryText: String = ""

override func viewDidLoad() {
    super.viewDidLoad()

    goals = firstGoals
    goalCategoryLabel?.text = goalCategoryText
    goalTableView.delegate = self
    goalTableView.dataSource = self
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "firstGoalsSegue" {
        if goalCategoryText == "First Goals" {
            let viewController = segue.destination as! GoalsViewController
            viewController.firstGoals.append(valueToPass)
        }
    }
    if segue.identifier == "secondGoalsSegue" {
        if goalCategoryText == "Second Goals" {
            let viewController = segue.destination as! GoalsViewController
            viewController.secondGoals.append(valueToPass)
        }
    }

}

extension GoalsViewController: UITableViewDelegate, UITableViewDataSource {

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "GoalsCell_1", for: indexPath)
    cell.textLabel?.text = goals[indexPath.row]
    cell.textLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping
    cell.textLabel?.numberOfLines = 3
    return cell
}

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return "\(sectionHeader)"
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    valueToPass = goals[indexPath.row]
    performSegue(withIdentifier: "firstGoalsSegue", sender: self)
    performSegue(withIdentifier: "secondGoalsSegue", sender: self)
    tableview.reloadData()
}
}

这是我的故事板。 故事板

当前,选择一个按钮时,我被带到只显示空单元格的桌面屏幕。我将如何修复我的代码,以便在点击受尊重的按钮时将 firstGoals 和 secondGoals 的值传递给 tableview?

标签: iosswiftuitableview

解决方案


您需要将GoalTableView'delegatedataSource设置为GoalsViewController,如下所示:

override func viewDidLoad() {
    super.viewDidLoad()

    goals = ["goal 1", "goal 2", "goal 3"]
    goalCategoryLabel?.text = goalCategoryText
    GoalTableView.delegate = self
    GoalTableView.dataSource = self
    GoalTableView.reloadData()
}

提示:尝试为实例保留以小写字母开头的名称,在这种情况下重命名GoalTableViewgoalTableView.


推荐阅读