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
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:
the same for image inside your custom cell
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;
}
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With