如何在TableView的每一行添加按钮、图片等UI元素? (iOS,Swift)

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

我可以使用 Swift 在 iOS 的 UITableView 中显示文本列表(每行一段文本)。我的问题是 - 如果我想在每一行中添加更多 UI 元素 - 例如按钮、图像等,我该怎么做?感谢 Swift.

的帮助

我已经能做的:

我使用的代码

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.
}


}

我有结果(如下)。我只能添加一个文本,如何添加更多元素?

从您的 main.storyboard 中,将 imageView、标签和任何您想要的内容拖到原型单元格中。

您还需要为拖入其中的每个元素建立 IBOutlets,以便您可以在代码中引用它们。

还有其他方法,比如选择单元格样式。例如,表格自带 4 种开箱即用的样式。基本样式具有 imageView 和标签。

如果您想要更强大的功能,样式应该是自定义的,您可以将需要的任何内容拖到原型单元格中。

如果样式是 "Default",您应该只能看到 textLabel 的文本。如果单元格的样式是 "Custom" 你可以添加更多的元素。然后您可以在 Interface Builder 中添加元素并建立出口或以编程方式将它们添加到单元格