Mateo Villagomez
Mateo Villagomez

Reputation: 52

Array of structures in table view

There are a few questions about array of structures but I can't find any answer. Thanks in advance. I have the following array of structures:

var datosLibros = [BookData]()

The structure has the following data:

struct BookData {
var title: String
var author: String
var image: UIImage?
var isbn: String

}

The user make a search with an isbn and the book data is saved into this structure and appended into datosLibros.The search results are append to datosLibros by the following code:

 let libro = BookData(title: bookTitle!, author: bookAuthor!, image: bookCover, isbn: termino)
 datosLibros.append(libro)

I need to retrieve each title for a the cell text in a table view. I have tried this:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
    for  i in datosLibros  {
        cell.textLabel?.text = i.title
    }
    return cell
}

It seems to be working but only until another search is made. Then, every cell title repeats itself with the last books title. Please tell me what I am doing wrong.

Upvotes: 0

Views: 622

Answers (1)

Callam
Callam

Reputation: 11539

You must retrieve the book from the array using indexPath.row as your array index. By using a for loop in the cellForItemAtIndexPath method, you're just setting the title of each cell to be the title of the last book in the array.

Try this:

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

    let book = datosLibros[indexPath.row]
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)

    cell.textLabel?.text = book.title

    return cell
}

After appending a book to datasLibros, you need to reload the table view using tableView.reloadData().

Upvotes: 4

Related Questions