2016-02-04 4 views
0

Я пытаюсь создать базовое приложение Swift для отображения автомобилей. У меня есть настройка UITableView. В настоящее время я определил две машины, но по какой-то причине отображается только 1.Ячейки UITableView отображаются только 1 ячейка

Model.swift

import Foundation 
import UIKit 

public enum CarColor { 
case White 
case Blue 
case Black 
case Red 
} 

class Model { 

var title: String 
var description: String 
var image: UIImage 
var color: CarColor 

init(titled: String, description: String, imageName: String){ 
    self.title = titled 
    self.description = description 
    if let img = UIImage(named:imageName){ 
     image = img 
    } else { 
     image = UIImage(named:"default")! 
    } 
    color = .White 
    } 
} 

ModelLine.swift

import Foundation 

class ModelLine { 

var name: String 
var models: [Model] 


init(named: String, includeModels: [Model]){ 
    name = named 
    models = includeModels 
} 

class func modelLines() -> [ModelLine]{ 
    return[self.hondaCRV(), self.hondaPilot()] 
} 

private class func hondaCRV() -> ModelLine { 
    var models = [Model]() 
    models.append(Model(titled:"2016 Honda CR-V", description:"All day and into the night, CR-V delivers dynamic crossover performance and style. It's also incredibly spacious, with luxury amenities at the top of its class.", imageName: "crv")) 
    return ModelLine(named:"Honda CR-V", includeModels: models) 
} 

private class func hondaPilot() -> ModelLine { 
    var models = [Model]() 
    models.append(Model(titled:"2016 Honda Pilot", description:"2016 Model", imageName: "pilot")) 
    return ModelLine(named:"Honda Pilot", includeModels: models) 
} 

HondaModelTableViewController.swift

import UIKit 

class HondaModelTableViewController: UITableViewController { 

var models: [Model]{ 
    var modelLines = ModelLine.modelLines() 
    return modelLines[0].models 
} 

override func viewDidLoad() { 
    super.viewDidLoad() 
} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
} 


override func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
    // #warning Incomplete implementation, return the number of sections 
    return 1 
} 

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


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier("modelCell", forIndexPath: indexPath) as UITableViewCell 

    let model = models[indexPath.row] 
    cell.textLabel?.text = model.title 
    cell.detailTextLabel?.text = model.description 
    cell.imageView?.image = model.image 

    return cell 
} 
+0

Это вопрос: вар modelLines = ModelLine.modelLines() возврата modelLines [0] .models. Тем не менее, ваш код выглядит немного ovecomplicated. – Lubos

ответ

1

Вы просто возвращает первый массив ModelLine, который имеет только один автомобиль в нем.

class func modelLines() -> [ModelLine]{ 
      //index 0   index 1 
    return[self.hondaCRV(), self.hondaPilot()] 
} 

var models: [Model]{ 
    var modelLines = ModelLine.modelLines() 
    return modelLines[0].models //Only index 0 being called. 
} 

Поскольку вы ваша модель создана в 2 мерных массив видов, видя, как self.hondaPilot() могут быть реализованы позже, чтобы вернуть более одного Model, я предлагаю создание вашей ModelLines в разделах и ваш Model как строк в этом разделе.

var modelLines : [ModelLines] { //Use modelLines instead so you have access to ALL cars of all modelLines. 
     return ModelLine.modelLines() 
    } 
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
     // #warning Incomplete implementation, return the number of sections4 
     return modelLines.count //This will give you 2 sections. 
    } 

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return modelLines[section].count //Gives you number of models in each modelLines section. 
    } 
+0

Я реорганизовал свою модель, чтобы у hondaCars были обе машины. Но спасибо! Отметьте это как правильное, так как это привлекло мое внимание чрезмерное усложнение моего дизайна. – Rami

1

В

var models: [Model]{ 
    var modelLines = ModelLine.modelLines() 
    return modelLines[0].models 
} 

Вы возвращаете только первый элемент из массива.

0

В HondaModelTableViewController вы возвращаете только первый объект массива modelLines.

Заменить return modelLines[0].models с:

for model in modelLines { 
    return model.models 
} 
0

в numberOfRowsInSection, вы возвращаете количество моделей в modelLines [0]

Вы загрузили Honda CR-V в modelLine [0], и Honda Пилот в modelLines [1]

Вы получаете только одну строку, потому что это то, сколько данных вы указали. Если вы хотите, и появляться в той же таблице, вам нужно разобраться в ваших Конструкторы

0

Части должны быть рассмотрены:



    // Part I: 
    // var models: [Model]{ 
    //  var modelLines = ModelLine.modelLines() 
    //  return modelLines[0].models 
    // } 
    let models = ModelLine.modelLines() 

    // Part II: 
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell 
     let model = models[indexPath.row].models[0] 
     cell.textLabel?.text = model.title 
     cell.detailTextLabel?.text = model.description 

     return cell 
    } 

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