简体   繁体   中英

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? 在此处输入图片说明

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM