2014-10-19 2 views
5

Я видел похожие вопросы, но я очень новичок в iOS и недостаточно понимаю, чтобы применить ответы на мой сценарий. Я делаю iPad-приложение с основными данными и хочу, чтобы в ландшафтном представлении отображалось два таблицы. Я не знаю, как указать второй tableView из моего файла vc.swift. Этот код отображает две идентичные таблицы. EDIT: теперь я могу указать разные таблицы, но я не могу отправлять разные кордаты каждому из них. Проблема, похоже, начинается с DidLoad, которая не может видеть tableView, поэтому каждый раз нужно извлекать все данные.ios, swift: несколько столов, единственный viewcontroller

данных из того же лица, он просто имеет различные атрибуты (вот почему я сделал функцию из playerFetchRequest, которая принимает параметр, - подумал я мог бы просто сделать различные Fetch запросов с дифф параметрами):

import UIKit 
import CoreData 

class CustomTableViewCell : UITableViewCell { 
    @IBOutlet var l1: UILabel? 
    @IBOutlet var l2: UILabel? 

    func loadItem(#number: String, name: String) { 
     l1!.text = number 
     l2!.text = name 
    } 
} 

class ViewController: UIViewController, UITableViewDelegate, NSFetchedResultsControllerDelegate, UITableViewDataSource { 

    @IBOutlet var tableView: UITableView! 
    //this is my second table - Ive connected it in the IB to this VC 
    @IBOutlet var tableView2: UITableView! 

    let managedObjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext 
    var fetchedResultController: NSFetchedResultsController = NSFetchedResultsController() 

    func playerFetchRequest(playerType: String) -> NSFetchRequest { 
     let fetchRequest = NSFetchRequest(entityName: "Players") 
     let sortDescriptor = NSSortDescriptor(key: "number", ascending: true) 
     let filterForwards = NSPredicate(format: "%K = %@", "type", playerType) 
     fetchRequest.sortDescriptors = [sortDescriptor] 
     fetchRequest.predicate = filterForwards 
     return fetchRequest 
    } 

    func getFetchedResultController(playerType: String) -> NSFetchedResultsController { 
     fetchedResultController = NSFetchedResultsController(fetchRequest: playerFetchRequest("Forward"), managedObjectContext:managedObjectContext!, sectionNameKeyPath: nil, cacheName: nil) 
     return fetchedResultController 
    } 

    //remember: to create a table with multiple sections just implement the numberOfSectionsInTableView(_:) method 
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     if let numberOfRowsInSection = fetchedResultController.sections?[section].numberOfObjects 
     {return numberOfRowsInSection} else {return 0} 
    } 

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     var cell:CustomTableViewCell = self.tableView.dequeueReusableCellWithIdentifier("customCell") as CustomTableViewCell 
     let player = fetchedResultController.objectAtIndexPath(indexPath) as DataModel 
     cell.l2?.text = player.lastName + ", " + player.firstName 
     cell.l1?.text = player.number 
     return cell 
    } 

    func tableView(tableView: UITableView!, didDeselectRowAtIndexPath indexPath: NSIndexPath!) { 
     tableView.deselectRowAtIndexPath(indexPath, animated: true) 
     println("You selected cell #\(indexPath.row)!") 
    } 

    override func viewDidLoad() { 
     var nib = UINib(nibName: "CustomTableViewCell", bundle: nil) 
     tableView.registerNib(nib, forCellReuseIdentifier: "customCell") 
     fetchedResultController = getFetchedResultController("Forward") 
     fetchedResultController.delegate = self 
     fetchedResultController.performFetch(nil) 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 
    func controllerDidChangeContent(controller: NSFetchedResultsController!) { 
     tableView.reloadData() 
    } 
} 
+0

Понял! на самом деле это были два вопроса: 1. как иметь две таблицы и 2. как иметь два fetchResControllers. Это сообщение ответило на первый, и этот ответил на второй. http://stackoverflow.com/questions/26461219/ios-swift-core-data-multiple-tables – wellspokenman

ответ

3

Я думаю, вы должны проверить этот путь

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
if ([tableView isEqual: tableView1]) { 
// Do something 
    } 

    else { // tableView == tableView2 
// Do something else 
    } 
} 

подобное для других методов Tableview.

+0

часть whats messing меня в том, что tableView1 на самом деле называется tableView. Я переименую его сейчас и посмотрю, все ли работает, а затем попытайтесь реализовать оператор if. – wellspokenman

+1

Вы можете использовать 'tableView', потому что существует разница между' tableView' локальной переменной и 'self.tableView' свойство – Paulw11

+0

согласен с Paulw11 –

Смежные вопросы