Dennis van Mazijk Dennis van Mazijk - 3 months ago 10
iOS Question

Swift - Add two array elements to detailTextLabel in tableView

I have a tableview with a list of students. Each cell contains the name of a student and a subtitle. I managed to add two elements to my subtitle by creating a constant and returning this data.

I am trying to display this:

(Textlabel) First Student

(Subtitle) Elementary, 5th grade

I am currently using this piece of code:

let subTitle = "\(student.level)\(", ")\(student.grade)"

cell!.detailTextLabel?.text = subTitle


Is it wise to do it like this? It's working, but I am not sure if this the best method.

Extended version of my code:

studentArray = [
Student(level: "Elementary", grade: "5th grade", name: "First student"),
Student(level: "Junior High", grade: "3rd grade", name: "Second student"),
Student(level: "High School", grade: "1st grade", name: "Third student")


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

var cell = tableView.dequeueReusableCellWithIdentifier("cellId")
if cell == nil {
cell = UITableViewCell(style: .Subtitle, reuseIdentifier: "cellId")
}

let student: Student

if searchController.active && (searchController.searchBar.text != "" || !filteredStudents.isEmpty) {
student = filteredStudents[indexPath.row]
} else {
student = studentArray[indexPath.row]
}

cell!.textLabel?.text = student.name
cell!.textLabel!.font = UIFont.systemFontOfSize(14)

cell!.textLabel?.text = student.name
cell!.textLabel!.font = UIFont.systemFontOfSize(14)

let subTitle = "\(student.level)\(", ")\(student.grade)"

cell!.detailTextLabel?.text = subTitle
cell!.detailTextLabel!.font = UIFont.systemFontOfSize(10)

return cell!
}

Answer

then alternate Way try this

   var subTitle = "\(student.level)"
    subTitle += ",\(student.grade)"

or use like

 let subTitle = "\(student.level),\(student.grade)"

finally append like

cell!.detailTextLabel?.text = subTitle
Comments