I\'d like a UITableView
with subtitle
-style cells that use dequeueReusableCellWithIdentifier
.
My original Objective-C code was
Keep in mind that UITableView
is defined as an optional in the function, which means your initial cell declaration needs to check for the optional in the property. Also, the returned queued cell is also optional, so ensure you make an optional cast to UITableViewCell
. Afterwards, we can force unwrap because we know we have a cell.
var cell:UITableViewCell? =
tableView?.dequeueReusableCellWithIdentifier(reuseIdentifier) as? UITableViewCell
if (cell == nil)
{
cell = UITableViewCell(style: UITableViewCellStyle.Subtitle,
reuseIdentifier: reuseIdentifier)
}
// At this point, we definitely have a cell -- either dequeued or newly created,
// so let's force unwrap the optional into a UITableViewCell
cell!.detailTextLabel.text = "some text"
return cell
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath:
NSIndexPath) -> UITableViewCell {
var CellIdentifier:String = "Cell"
var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier(CellIdentifier) as? UITableViewCell
if cell == nil {
cell = UITableViewCell(style:UITableViewCellStyle(rawValue:3)!,reuseIdentifier:CellIdentifier)
}
return cell!
}
I engage you to look at this little UITableView-Example on Github: https://github.com/YANGReal/UITableView-Swift
They do like follows:
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
{
let cell = tableView .dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
cell.textLabel.text = String(format: "%i", indexPath.row+1)
// set any other property of your cell here
return cell
}
You can use a slightly different syntax than the one from memmons to prevent the forced unwrapping:
let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier) as? UITableViewCell ?? UITableViewCell(style: .Subtitle,
reuseIdentifier: reuseIdentifier)
cell.detailTextLabel?.text = "some text"
return cell
This is using XCode 6.1 7, Swift 1.2 2.0 syntax where UITableView
is no longer an optional.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
var cell:UITableViewCell? =
tableView.dequeueReusableCell(withIdentifier: "cell")
if (cell != nil)
{
cell = UITableViewCell(style: UITableViewCellStyle.subtitle,
reuseIdentifier: "cell")
}
cell!.textLabel?.text = "ABC"
cell!.detailTextLabel?.text = "XYZ"
return cell!
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let reuseIdentifier = "cell"
var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier) as UITableViewCell?
if (cell == nil) {
cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: reuseIdentifier)
}
cell!.textLabel?.text = self.items[indexPath.row]
cell!.detailTextLabel?.text = self.items[indexPath.row]
return cell!
}