2015-06-14 2 views
0

В последнем вопросе, который я задал о ошибке кода в моем проекте просмотра таблицы животного, теперь я закончил исходное кодирование, но мой интерфейс стал действительно странным. В нем отсутствует первая буква имени каждого животного и ячейка прототипа таблицы. Например, amel должен быть верблюдом и hinoceros должен быть носорогом. Это ошибка от кода здесь?Ошибка отображения таблицы UI: Swift

import UIKit 

class AnimalTableViewController: UITableViewController { 

var animalsDict = [String: [String]]() 
var animalSelectionTitles = [String]() 

let animals = ["Bear", "Black Swan", "Buffalo", "Camel", "Cockatoo", "Dog", "Donkey", "Emu", "Giraffe", "Greater Rhea", "Hippopotamus", "Horse", "Koala", "Lion", "Llama", "Manatus", "Meerkat", "Panda", "Peacock", "Pig", "Platypus", "Polar Bear", "Rhinoceros", "Seagull", "Tasmania Devil", "Whale", "Whale Shark", "Wombat"] 

func createAnimalDict() { 
    for animal in animals { 
     let animalKey = animal.substringFromIndex(advance(animal.startIndex, 1)) 
     if var animalValues = animalsDict[animalKey] { 
      animalValues.append(animal) 
      animalsDict[animalKey] = animalValues 
     } else { 
      animalsDict[animalKey] = [animal] 
     } 
    } 
    animalSelectionTitles = [String] (animalsDict.keys) 
    animalSelectionTitles.sort({ $0 < $1}) 
    animalSelectionTitles.sort({ (s1:String, s2:String) -> Bool in 
     return s1 < s2 
    }) 
} 

override func viewDidLoad() { 
    super.viewDidLoad() 

    createAnimalDict() 
} 

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

// MARK: - Table view data source 

override func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
    // Return the number of sections. 
    return animalSelectionTitles.count 
} 

override func tableView(tableView: UITableView, titleForHeaderInSection section:Int) -> String? { 
    // Return the number of rows in the section. 
    return animalSelectionTitles[section] 

} 


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

    let animalKey = animalSelectionTitles[indexPath.section] 
    if let animalValues = animalsDict[animalKey] { 
     cell.textLabel?.text = animalValues[indexPath.row] 
     let imageFileName = animalValues[indexPath.row].lowercaseString.stringByReplacingOccurrencesOfString("", withString: "_", options: nil, range: nil) 
     cell.imageView?.image = UIImage(named:imageFileName) 
    } 
    return cell 
} 

}

+0

Вы проверили, что 'animalsDict' содержит то, что вы ожидаете? И не должно быть 'substringToIndex' вместо' substringFromIndex', как уже было предложено в ответе на ваш предыдущий вопрос? Вы установили точку останова в 'titleForHeaderInSection' и' cellForRowAtIndexPath' и использовали ** отладчик **, чтобы проверить, откуда взялись «неправильные» имена? –

ответ

0

В этом методе:

override func tableView(tableView: UITableView, titleForHeaderInSection section:Int) -> String? { 
    // Return the number of rows in the section. (THIS COMMENT IS INCORRECT) 
    return animalSelectionTitles[section] 
} 

Вы возвращаете название для каждого раздела. Однако ваш animalSelectionTitles[index] содержит название животного, без первой буквы из-за своей конструкции в createAnimalDict

использовать массив животных вместо предоставления полных названий животных:

override func tableView(tableView: UITableView, titleForHeaderInSection section:Int) -> String? {   
    return animals[section] 
} 

Однако обратите внимание, что в связи с удалением первого письмо, у вас может быть два животных, сопоставляющих один и тот же ключ, поэтому, если это не обязательно, используйте все имя животного в качестве ключа.

1

До сих пор я могу сказать, что ошибка в вашем методе createAnimalDict(). В строке

let animalKey = animal.substringFromIndex(advance(animal.startIndex, 1)) 

обмен второй параметр заранее равным 0, то:

let animalKey = animal.substringFromIndex(advance(animal.startIndex, 0)) 

На самом деле я не знаю, что вы пытаетесь сделать.

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