Jeppe Christensen Jeppe Christensen - 1 month ago 9
Swift Question

How to put a subtitle label under textlabel in cell?

I have a tableView, which I have put 2 text labels (I need 3 when I'm done).
Both labels shows up, but my issue is that the

detailTextLabel
is inline with the
titlelabel
which it obviously shouldn't be.

I have tried to add dynamic sizing to the rows because I thought that the height of the cells was what constrained the detailtext label to fit on a line below
titlelabel
.
That was not the case though.

This is what I have:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var myCell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier")
if myCell == nil {
myCell = UITableViewCell(style: .value1, reuseIdentifier: nil)
myCell = UITableViewCell(style: .value2, reuseIdentifier: nil)
}
let item: Parsexml = feedItems[indexPath.row] as! Parsexml
myCell?.textLabel!.text = item.name! + " | " + item.address!
myCell?.detailTextLabel?.text = "Category:" + item.city!
myCell?.textLabel?.textColor = UIColor(white: 1, alpha: 1)
myCell?.textLabel?.font = UIFont(name: "HelveticaNeue-Bold", size: 12)
myCell?.detailTextLabel?.font = UIFont(name: "HelveticaNeue", size: 8)
myCell?.detailTextLabel?.textColor = UIColor(white: 1, alpha: 0.3)

return myCell!
}


How do I force my
detailtextlabel
to sit below my
titlelabel
?

Answer

First of all, the first assignment inside the following IF is useless because it is overwritten by the next assignment.

if myCell == nil {
    myCell = UITableViewCell(style: .value1, reuseIdentifier: nil)
    myCell = UITableViewCell(style: .value2, reuseIdentifier: nil)
}

By the way, you nee to use the .subtitle style, not .value2.

So replace this

if myCell == nil {
    myCell = UITableViewCell(style: .value1, reuseIdentifier: nil)
    myCell = UITableViewCell(style: .value2, reuseIdentifier: nil)
}

with this

if myCell == nil {
    myCell = UITableViewCell(style: .subtitle, reuseIdentifier: nil)
}

Removing the optional

Even better you can make myCell a non optional value

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var myCell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier")
        ?? UITableViewCell(style: .subtitle, reuseIdentifier: nil)

    let item: Parsexml = feedItems[indexPath.row] as! Parsexml
    myCell.textLabel!.text = item.name! + " | " + item.address!
    myCell.detailTextLabel?.text = "Category:" + item.city!
    myCell.textLabel?.textColor = UIColor(white: 1, alpha: 1)
    myCell.textLabel?.font = UIFont(name: "HelveticaNeue-Bold", size: 12)
    myCell.detailTextLabel?.font = UIFont(name: "HelveticaNeue", size: 8)
    myCell.detailTextLabel?.textColor = UIColor(white: 1, alpha: 0.3)

    return myCell
}