简体   繁体   中英

Swift adding image icons to UITableViewController

I was trying to import separate image icons next to my tableview cells using this code

switch(Anime)   {
    case 0:       
        var bleachimage = UIImage(named: "bleach icon")
        cell.imageView?.image  = bleachimage
    }

But I keep getting an error marked at case 0 saying type int does not conform to protocol IntervalType .

I'm using Swift by the way with Xcode 6.1

I also read before posting this that I was supposed to be switching the cell index not the array, I tried it and failed so maybe I'm doing something wrong?

Thx for the help.

Assuming that:

  1. Your array anime (yes it's Anime but you should use the lowercase for the first char) has n elements where n is the number of the cells in your table
  2. Each element of anime is a tuple
  3. The first element of the tuple (declared at bullet 2) is a String representing the name of the image locally stored

You can add an image to each cell with this code:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("myCell") as? UITableViewCell
        ?? UITableViewCell(style: .Default, reuseIdentifier: "myCell")
    let tuple = self.anime[indexPath.row]
    cell.imageView?.image = UIImage(named: tuple.0)
    return cell
}

Hope this helps.

Update to better answer the comment

The method above is called by iOS for every cell that needs to be displayed. Each time it is called with an indexPath referring a specific cell.

Eg if iOS need to display cell 0 in section 0 (the first cell in your table) the indexPath will have the row property equals to 0 and section equals to 0 . For cell 1 in section 0 , the index path will have row equals to 1 and section equals to 0 . And so on...

So, what I am doing inside this method? I am accessing the element indexPath.row of array anime , in order to retrieve the tuple needed to populate the cell at position indexPath.row . Next I extract the first element of the tuple (a string containing the name of the image) and I use that value to build a UIImage . Next I assign that image to the current cell. Finally I return the cell.

Just try it. If the assumptions are correct, it will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM