如何在普通 UIViewController 中使用 UITableView

2025-04-25 20:25:48
推荐回答(1个)
回答1:

1. 新建 Application

2. 添加一个 Table View

3. 在 Table View 上添加一个 Table View Cell

4. 在左侧选中该 Table View Cell,并赋予它 Identifier
左侧,点击选中:

右侧,在 Identifier 框里面输入小写的 cell ,输入完成后记得按 Enter 确认:

5. 将该 Table View 绑定到代码

取名为 firstTableView。
6. 修改代码
import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var firstTableView: UITableView!

override func viewDidLoad() {
super.viewDidLoad()

firstTableView.delegate = self
firstTableView.dataSource = self
}

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

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell

cell.textLabel.text = "我是第 \(indexPath.row) 个Cell"

return cell
}

}