Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom table view cell with swift in xcode 6

So, I created a custom table view cell with a label on the left and a UIImageView on the right. The label has a tag of 100 and the UIImageView a tag of 110.

My code is the following:

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

    var cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier("ThemeCell") as UITableViewCell

    let theme = themes[indexPath.row]

    var themeName = cell.viewWithTag(100) as? UILabel
    themeName?.text = theme.themeName

    let themeImage = cell.viewWithTag(110) as? UIImageView
    themeImage?.image = UIImage(named: "test.png")

    //1
    //cell.imageView?.image = UIImage(named: "test.png")

    println("The loaded image: \(themeImage?.image)")

    return cell;
}

As is is, the themeName is displayed but the themeImage does not appear, although from println it seems that the image is loaded. If I uncomment the code in 1 the image appears in the custom cell but of course does not appear in the proper place as it is not added to the UIImageView that I created in IB. Any ideas what I might be doing wrong? The Tags are all correct. Thanks

like image 908
μ4ρκ05 Avatar asked Sep 23 '14 16:09

μ4ρκ05


2 Answers

Firstly, you need to pin your views with auto layout mechanism. Open interface builder, left click on label inside your custom cell, then for example do the following:

  1. Editor->Pin->Width
  2. Editor->Pin->Height
  3. Editor->Pin->Leading Space to Superview
  4. Editor->Pin->Top Space to Superview

the same for image inside your custom cell

  1. Editor->Pin->Width
  2. Editor->Pin->Height
  3. Editor->Pin->Trailing Space to Superview
  4. Editor->Pin->Top Space to Superview

Then create custom class for your cell. for example

MyCustomCell.swift

import Foundation
import UIKit

class MyCustomCell: UITableViewCell {
    @IBOutlet weak var myLabel: UILabel!
    @IBOutlet weak var myImageView: UIImageView!
}

Then set custom class for your cell and create connections from elements.

And now in tableViewController you can set the values to your elements without tags:

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

    var cell: MyCustomCell = tableView.dequeueReusableCellWithIdentifier("ThemeCell") as MyCustomCell

    let theme = themes[indexPath.row]

    cell.myLabel.text = theme.themeName
    cell.myImageView.image = UIImage(named: "test.png")

    println("The loaded image: \(cell.myImageView.image)")

    return cell;
}
like image 53
imike Avatar answered Sep 30 '22 21:09

imike


Ok, so the fault was not in the UITable at all but in the fact that the AutoLayout was not set correctly and the image appeared outside the tableview...

like image 43
μ4ρκ05 Avatar answered Sep 30 '22 19:09

μ4ρκ05