简体   繁体   English

Swift:如何获取表行单元格(indexPath)并从详细视图控制器的数据模型中加载它?

[英]Swift: How to get the table row cell (indexPath) and load it from the data model in detail view controller?

It took me while to get the core data model working and I can create content in a detail view controller and pass it to my table view to display the newly created row in the table, but I cannot find out how to correctly display the data in the detail view controller again. 我花了一些时间才能使核心数据模型正常工作,我可以在详细信息视图控制器中创建内容并将其传递到我的表视图以显示表中新创建的行,但是我无法找到如何正确显示其中的数据的方法。详细视图控制器再次。

Since I am using core data, I was thinking about just getting the index path for the selected table view row and pass it to the detail view controller, where the appropriate data would be loaded from the data model array, but how to pass the indexPath to the detail view controller and load the data? 由于我使用的是核心数据,因此我在考虑仅获取所选表视图行的索引路径,并将其传递给详细信息视图控制器,在该控制器中,将从数据模型数组中加载适当的数据,但是如何传递indexPath到详细视图控制器并加载数据?

在此处输入图片说明

There is only one barButtonItem in my master view to add new content - plus the tableView. 我的主视图中只有一个barButtonItem可以添加新内容-以及tableView。

In my tableView I fetch and display the data like this: 在我的tableView中,我获取并显示如下数据:

var managedObjectContext: NSManagedObjectContext!    
var coasters = [Coaster]()


override func viewDidLoad() {
        super.viewDidLoad()

        // Add NoteficationCenter observer to reload table from another view.
        NotificationCenter.default.addObserver(self, selector: #selector(loadData), name: NSNotification.Name(rawValue: "reload"), object: nil)

        // Initialize Core Data ManagedObjectContext
        managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

        loadData()
    }


@objc func loadData() {
        let coasterRequest: NSFetchRequest<Coaster> = Coaster.fetchRequest()

        // Sorting from newest to oldest.
        let sortDescriptors = NSSortDescriptor(key: "date", ascending: false)
        coasterRequest.sortDescriptors = [sortDescriptors]

        // Attempt to load data from Core Data!
        do {
            coasters = try managedObjectContext.fetch(coasterRequest)
            self.tableView.reloadData()
        } catch {
            print("loading error: \(error.localizedDescription)")
        }
    }


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CoasterTableViewCell

        let coasterItem = coasters[indexPath.row]

        if let coasterImage = UIImage(data: coasterItem.image as! Data) {
            cell.bacgkgroundImageView.image = coasterImage
        }

        cell.nameLabel.text = coasterItem.name
        cell.parkLabel.text = coasterItem.park
        cell.dateLabel.text = coasterItem.date

        cell.countLabel.text = String(coasterItem.counter)

        return cell
    }

To explain this: In the detail view controller everything is saved to core data when the user hits "save" and returns to master view. 对此进行解释:在详细视图控制器中,当用户单击“保存”并返回主视图时,所有内容都保存到核心数据中。 I added a simple Notification Center observer which is triggered from the detail view controller and tells the master view to reload the data (that was the easiest for me to reload everything without using the prepare function. And it works perfectly. 我添加了一个简单的Notification Center观察器,该通知器从详细信息视图控制器触发,并告诉主视图重新加载数据(这对我来说最简单的方法是不使用prepare函数重新加载所有数据。它工作得很好。

Now to the problem: So when the user clicks on a table view cell the indexPath should be passed to the detail view and there it should load the correct data from the data model (obviously I guess I have to check whether the user wants to add something or just views the content). 现在解决问题:因此,当用户单击表视图单元格时,应将indexPath传递到详细信息视图,并在该视图中从数据模型中加载正确的数据(显然,我想我必须检查用户是否要添加或只是查看内容)。 How can this be done? 如何才能做到这一点? I hope this is all you need, if I should add something just ask. 我希望这就是您所需要的,如果我要补充一点,请问。

try like this 这样尝试

extension MasterViewController: UITableViewDelegate{
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        //here 'self.tableDataSourceArray' is the data set fetched from the database
        let selectedObject = self.tableDataSourceArray[indexPath.row]
        // pass 'selectedObject' to the detail viewcontroller
        let detail = ......
        detail.currentObjectToDisplay = selectedObject

        //in case, if you are using same view controller to add new info and show the existing info, you are required to take one more property in the detail viewcontroller to handle the data
        detail.addMode = false //'true' if you are adding
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何快速在索引路径委托的行中的单元格中加载自定义表格视图单元格 - How to load a custom table view cell in cell for row at indexpath delegate in swift 如何通过索引路径方法中的didselect行从一个视图控制器调用表数据到另一个视图控制器 - how to call table data from one view controller to another via didselect row at indexpath method 如何从表格视图单元格中的图像手势获取 indexPath - How to get indexPath from image gesture in table view's cell 如何从行索引Swift获取indexpath - How to get indexpath from row index Swift 从表视图中删除单元格后更新indexPath.row - Updating indexPath.row after deleting a cell from table view 单击表格视图单元格上的按钮时如何获取indexPath.row? - How to get the indexPath.row when I click a button on a table view cell? 如何在索引路径的行中显示单元格中的数据模型内容? - How to Display data model content in cell for row at indexpath? 关于表视图单元格indexpath.row - About table view cell indexpath.row Swift 3将单元格数据A视图传递到B视图,有趣的是didSelectRowAt indexPath在选择行后崩溃 - Swift 3 pass the cell data A view to B view, with fun didSelectRowAt indexPath crash after select row 如何根据表视图单元格的详细文本标签,将segue设置为与表视图控制器不同的视图控制器? - How can I set a segue to a different view controller from a table view controller, based on the detail text label of the table view cell?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM