Пожалуйста, простите, если это дублированный вопрос. Я выполнял поиск настолько тщательно, насколько мог, но ни один из других вопросов, которые я видел относительно основных данных в UITableView, по-видимому, не подходит для того, что я пытаюсь сделать.Нужна помощь в отображении основных данных в UITableView в Swift
В принципе, у меня есть два "таблицы" в моем Core Data:
cstProjects и plProjects
Обе таблицы имеют атрибуты называются "propertyOwner" и "PropertyID" (среди прочих), которые устанавливаются в качестве строк ,
Далее, в ViewController у меня есть экземпляр табличного представления со стилем, установленным в Subtitle, а идентификатор ячейки - «projectCell».
Поскольку у меня есть две таблицы в моих основных данных, я инициализирую таблицу двумя разделами. Я хотел бы, чтобы первый раздел показывал все проекты в таблице cstProjects, а второй раздел показывал все проекты в таблице plProjects.
Вот мой код ViewController. Я вложил комментарии, чтобы объяснить это как можно лучше. Функции, которые я создал, могут немного переборщить, чтобы выяснить, сколько «строк» каждого раздела должно иметь, но я не знал о более простом способе его решения.
В коде внизу, где отображаются двойные вопросительные знаки "??" где я не уверен, что нужно сделать, чтобы показать текущую «строку» типа проекта, который мы сейчас итерируем.
В конечном итоге, если бы мне пришлось как можно больше упростить мой вопрос, мне просто нужно знать, как отображать строки таблицы данных ядра в UITableView.
import UIKit
import CoreData
class LoadProjectViewController: UIViewController, UITableViewDataSource, NSFetchedResultsControllerDelegate {
let projectSectionCount: Int = 2
let cstSection: Int = 0
let plSection: Int = 1
// Implement UITableViewDataSource methods
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return projectSectionCount
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch(section) {
case cstSection:
return getCSTProjects()
case plSection:
return getPLProjects()
default:
return 0
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier("projectCell")! as UITableViewCell
switch (indexPath.section) {
case cstSection:
//this is where I need to set the property owner for the CST Project
cell.textLabel!.text = ??
//this is where I need to set the project ID for the CST Project
cell.detailTextLabel!.text = ??
case plSection:
//this is where I need to set the property owner for the PL Project
cell.textLabel!.text = ??
//this is where I need to set the project ID for the PL Project
cell.detailTextLabel!.text = ??
default:
cell.textLabel!.text = "Unknown"
}
return cell
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case cstSection:
return "Standing Timber Projects"
case plSection:
return "Purchased Logs"
default:
return "Unknown"
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getCSTProjects() -> Int {
let appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
let context: NSManagedObjectContext = appDel.managedObjectContext
let request = NSFetchRequest(entityName: "CSTProjects")
var results = [AnyObject]()
request.returnsObjectsAsFaults = false
do {
results = try context.executeFetchRequest(request)
} catch let error {
print("There was an error loading the data. \(error)")
}
if (results.count > 0) {
return results.count
} else {
return 0
}
}
func getPLProjects() -> Int {
let appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
let context: NSManagedObjectContext = appDel.managedObjectContext
let request = NSFetchRequest(entityName: "PLProjects")
var results = [AnyObject]()
request.returnsObjectsAsFaults = false
do {
results = try context.executeFetchRequest(request)
} catch let error {
print("There was an error loading the data. \(error)")
}
if (results.count > 0) {
return results.count
} else {
return 0
}
}
}