2015-05-27 2 views
1

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

Я создал табличный вид с разделами, но мое приложение падает, когда я дойду до конца списка. Я добавил код ниже с моментальным снимком представления таблицы и ошибки.

@IBOutlet weak var dishtable: UITableView! 

@IBOutlet weak var namlbl: UILabel! 
var Dishes = ["POPULAR Dishes": ["Biryani", "Tandori Chicken","Butter Chicken", "Vada Pav"],"A": ["Aloo baingan", "Aloo ki Tikki", "Amritsari fish"], "B": ["Baigan bharta", "Biryani"]]; 


override func viewDidLoad() { 
    super.viewDidLoad() 
    self.dishtable.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell") 
    dishtable.dataSource = self 
    dishtable.delegate = self 
    // Do any additional setup after loading the view. 
} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 
override func prefersStatusBarHidden() -> Bool { 
    return true 
} 

let sections:Array<AnyObject> = ["POPULAR Dishes","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"] 
var usernames = [String]() 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ 

    let cellID = "cell" 

    let cell: UITableViewCell = self.dishtable.dequeueReusableCellWithIdentifier(cellID) as! UITableViewCell 
    println("value : \(indexPath.section)") 
    println("value 1: \(indexPath.row)") 

    cell.textLabel!.text = Dishes[sections[indexPath.section] as! String]![indexPath.row] 

    return cell 

} 

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ 
    println("Dishes section count : \(section)") 

    return Dishes.count 
} 
func numberOfSectionsInTableView(tableView: UITableView) -> Int{ 

    return 27 
} 

func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { 

} 


func tableView(tableView: UITableView, 
    sectionForSectionIndexTitle title: String, 
    atIndex index: Int) -> Int{ 

     return index 
} 

func tableView(tableView: UITableView, 
    titleForHeaderInSection section: Int) -> String?{ 

     return self.sections[section] as? String 
} 

Это скриншот для табличного вида.

Table view

Это скриншот ошибки, когда я прокрутите вниз до нижней части представления таблицы.

error while scrolling down

Это скриншот консоли для одной и той же ошибки.

error shown in the console

Пожалуйста, дайте мне знать, как мы можем добавить функцию поиска в виде таблицы.

ответ

4

Я думаю, ваш вопрос лежит здесь:

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ 
    println("Dishes section count : \(section)") 

    return Dishes.count 
} 

Вы возвращаете количество строк для каждой секции, но нет блюд мимо ключ B в Dishes. Обычно в методе с numberOfRowsInSection делегата вы могли бы сделать что-то вроде этого:

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ 
    println("Dishes section count : \(section)") 

    if section == 0 { 
    return Dishes["POPULAR Dishes"].count 
    } 
    else if section == 1 { 
    return Dishes["A"].count 
    } 
    return 0 
} 

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

4

Проблема в numberOfRowsInSection функция.

Как и в вашем случае numberOfSectionsInTableView = 27, так что вам нужно вернуть индивидуальное numberOfRowsInSection.

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    switch section { 
    case 0: 
     return Dishes["POPULAR Dishes"].count 
    case 1: 
     return Dishes["A"].count 
    case 2: 
     return Dishes["B"].count 

    // upto case 26  
    default: 
     println("fetal error") 
    } 
    return 1 
} 
Смежные вопросы