如何连接到tableview容器?

时间:2018-03-27 07:23:33

标签: ios swift xcode uitableview core-data

我是Xcode和Swift的初学者,我目前正在创建一个应用程序,用户在应用程序中添加一个人,然后就是他们欠那个人或那个人欠他/她的钱。

注意:我已使用核心数据存储所有值

我有一个名为PeopleTableViewController的ViewController,用户在其中添加了他们所欠人的名字。然后我有PersonDetailTableViewController,它显示用户欠PeopleTableViewController中所选特定人员的详细信息列表。我面临的问题是,如果我在PeopleTableViewController中添加三个人,当我选择其中任何一个人时,我会被引导到PersonDetailTableViewController中的同一个tableview,但我想要用户在PeopleTableViewController中选择的不同人的不同表视图。

PersonDetailTableViewController:

import UIKit

class PersonDetailTableViewController: UITableViewController {

    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext


    var totalLabel: UILabel?
    var person: People?
    var owe: Owe?

    @IBOutlet var personTable: UITableView!

    var dataInfo: [Owe] = []
    var selectedObject: [Owe] = []
    var balanceAmount = "Balance: "

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

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = personTable
            .dequeueReusableCell(withIdentifier: "detailsCell", for: indexPath)
        cell.textLabel?.text = dataInfo[indexPath.row].name
        cell.detailTextLabel?.text = "₹ \(dataInfo[indexPath.row].amount)"
//        if dataInfo[indexPath.row].amount < 0 {
//            cell.detailTextLabel?.textColor = UIColor.red
//        } else {
//            cell.detailTextLabel?.textColor = UIColor.green
//        }
        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        selectedObject = [dataInfo[indexPath.row]]
        performSegue(withIdentifier: "addOweDetails", sender: nil)
        tableView.deselectRow(at: indexPath, animated: true)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        getData()
        personTable.dataSource = self
        addTotalToNav()
        print(dataInfo as Any)
    }



    // MARK: - Table view data source

    func addTotalToNav() -> Void {
        if let navigationBar = self.navigationController?.navigationBar {
            let totalFrame = CGRect(x: 10, y: 0, width: navigationBar.frame.width/2, height: navigationBar.frame.height)

            totalLabel = UILabel(frame: totalFrame)
            totalLabel?.text = balanceAmount
            totalLabel?.tag = 1
            totalLabel?.font = UIFont.boldSystemFont(ofSize: 14)
            totalLabel?.textColor = UIColor.red
//            navigationBar.large = totalLabel?.text
            self.title = totalLabel?.text

        }
    }


    func getData() -> Void {
        do{
            dataInfo = try context.fetch(Owe.fetchRequest())
            var total:Double = 0.00
            for i in 0 ..< dataInfo.count {
                total += dataInfo[i].amount as! Double
            }
            balanceAmount = "Balance: ₹" + (NSString(format: "%.2f", total as CVarArg) as String)
        }
        catch{
            print("Fetching Failed")
        }
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let vc = segue.destination as! NewOweTableViewController
        vc.dataInfo = selectedObject
        selectedObject.removeAll()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        getData()
        personTable.reloadData()
        if (self.navigationController?.navigationBar.viewWithTag(1)?.isHidden == true){
            self.navigationController?.navigationBar.viewWithTag(1)?.removeFromSuperview()
            addTotalToNav()
        }
    }

}

PeopleTableViewController:

import UIKit
import CoreData

class PeopleTableViewController: UITableViewController {

    @IBOutlet weak var peopleTableView: UITableView!

    var people: [People] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        peopleTableView.separatorStyle = .none

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem
    }

    //ViewWillAppear allows us to fetch all the data in the backend and help us display to the user
    override func viewWillAppear(_ animated: Bool) {
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
            return
        }

        let managedContext = appDelegate.persistentContainer.viewContext

        let fetchRequest: NSFetchRequest<People> =  People.fetchRequest()

        do {
            people = try managedContext.fetch(fetchRequest)

            peopleTableView.reloadData()
        } catch {
            print("Could not fetch")
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    @IBAction func addButtonPressed(_ sender: UIBarButtonItem) {
    }

    //Following function is called right before the user segues from one viewcontroller to another viewcontroller

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        guard let destination = segue.destination as? PersonDetailTableViewController,
           let selectedRow = self.peopleTableView.indexPathForSelectedRow?.row else {
            return
        }

        destination.person = people[selectedRow]
//        destination.owe = people[selectedRow]

    }

    func deletePerson(at indexPath: IndexPath) {
        let person = people[indexPath.row]

        guard let managedContext = person.managedObjectContext else {
            return
        }

        managedContext.delete(person)

        do {
            try managedContext.save()

            people.remove(at: indexPath.row)

            peopleTableView.deleteRows(at: [indexPath], with: .automatic)
        } catch {
            print("Could not delete")

            peopleTableView.reloadRows(at: [indexPath], with: .automatic)
        }
    }
}

extension PeopleTableViewController{

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

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

        let cell = peopleTableView.dequeueReusableCell(withIdentifier: "peopleCell", for: indexPath)

        let person = people[indexPath.row]

        cell.textLabel?.text = person.title

        return cell
    }

    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            deletePerson(at: indexPath)
        }
    }
}

以下图片显示了我的确切要求:

PeopleTableViewController

PeopleTableViewController

点击Mike,我得到以下信息:

PersonDetailTableViewController

点击John,我得到以下信息:

PersonDetailTableViewController

我希望Mike和John的记录与PersonDetailTableViewController上的记录不同。

1 个答案:

答案 0 :(得分:1)

您可以尝试(PeopleTableViewController中的两者),从shoePersonDetailsPeopleTableViewController创建一个名为PersonDetailTableViewController的segue

 override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let person = people[indexPath.row]
    performSegue(withIdentifier: "shoePersonDetails", sender: person)
    tableView.deselectRow(at: indexPath, animated: true)
}

//

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let vc = segue.destination as! PersonDetailTableViewController
    vc.dataInfo = sender as! People

}