user1406716
user1406716

Reputation: 9705

How to add buttons, images and other UI elements in each row of TableView? (iOS,Swift)

I am able to display a list of text (one piece of text in each row) in UITableView in iOS using Swift. My question is - what if I wanted to add more UI Elements in each row - like a button, image, etc. How can I do that? Would appreciate the help for Swift.

What I am already able to do:

Code I use

class ViewController: UIViewController, UITableViewDelegate {

var cellInfo = ["Rob", "Timmy", "George"]

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}


func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return 3
}

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

    let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "mycell") //my cell is the identifier

    cell.textLabel?.text = cellInfo[indexPath.row] //"Test"


    return cell

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}

Result I have (below). I am only able to add a text, how to add more elements? enter image description here

Upvotes: 0

Views: 1299

Answers (2)

mikemm13
mikemm13

Reputation: 81

If the style is "Default" you should only see the text of the textLabel. If the style of the cell is "Custom" you can add more elements. And then you can add elements in Interface Builder and establish outlets or add them to the cell programmatically

Upvotes: 1

Kelvin Lau
Kelvin Lau

Reputation: 6771

From your main.storyboard, drag the imageView, labels, and whatever you want into the prototype cell.

You'll also need to establish the IBOutlets for each element you drag in there so you can reference them in your code.

There are other ways, like selecting the cell style. For example, tables comes with 4 styles out of the box. The basic style features a imageView and label.

If you want more power, the style should be custom and you will drag whatever you need to the prototype cell.

Upvotes: 2

Related Questions