ios - 通过委托(delegate)附加的数据未显示在表上

标签 ios swift

我有一个协议(protocol),仅用于在 View Controller 之间传递数据。

protocol CreateWorkoutDelegate {
    func passedWorkout(workout : cellData)
}

出于某种原因,附加到 workoutArray 可以正常工作,但它没有显示在我的表格 View 中。

非常感谢所有帮助!

import UIKit

struct cellData {
    let workoutName : String!
    let workoutSets : Int
    let workoutReps : Int
}

class MainScreen: UIViewController, UITableViewDelegate, UITableViewDataSource, CreateWorkoutDelegate {

    @IBOutlet weak var tableView: UITableView!

    var workoutArray = [cellData]()

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self

    }

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = Bundle.main.loadNibNamed("CellData", owner: self, options: nil)?.first as! CellData

        cell.workoutNameLabel.text = workoutArray[indexPath.row].workoutName
        cell.setsNumberLabel.text = String(workoutArray[indexPath.row].workoutSets)
        cell.repsNumberLabel.text = String(workoutArray[indexPath.row].workoutReps)

        return cell

    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "createWorkout" {
            let createWorkoutVC : CreateWorkout = segue.destination as! CreateWorkout
            createWorkoutVC.delegate = self
        }
    }

    func passedWorkout(workout: cellData) {
        print(workoutArray.count)
        print(workout)
        workoutArray.append(workout)
        print(workoutArray.count)
    }


    @IBAction func AddWorkout(_ sender: UIButton) {
        performSegue(withIdentifier: "createWorkout", sender: self)

    }
}

最佳答案

您需要在附加数组后调用 tableView.reloadData() ,以便系统调用您的 UITableViewDataSource 委托(delegate)方法,从而使用新的填充 TableView 数据。

关于ios - 通过委托(delegate)附加的数据未显示在表上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45489733/

相关文章:

ios - 是否应该为已发布的应用关闭 NSZombieEnabled?

ios - cordova-plugin-camera:IOS 设备上出现崩溃错误 “No Image Selected”

ios - 为什么 iOS 11 : self. performSegue() 不工作?

ios - Swift 中的普通日期格式 "13th June 2007"

ios - 一个 viewcontroller swift 中的两个 TableView

ios - 应用间录音时点击

ios - 使用 NSOperations 时关联 NSManagedObjectContexts

ios - 将文档从 iMessage 导入应用程序 - 删除放置在 "Inbox"中的临时文件

iOS:应用程序挂起状态下的位置更新

ios - PrimaryViewController的UINavigationBar嵌入到UITabBarController后变色