Swift:使用界面构建器创建tableView

时间:2014-06-11 11:18:10

标签: ios uitableview swift

我试图在我的应用中实现tableView,虽然这对于objective-c没有问题我不知道如何在Swift中执行此操作。这是我的代码:

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet
var tableView: UITableView

override func viewDidLoad() {
    super.viewDidLoad()

    self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
}


func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
    return 5
}

func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
    var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell

    cell.textLabel.text = "test"

    return cell
}
}

我还在界面构建器中创建了一个带有原型单元格的tableView。原型单元的重用标识符设置为" cell"。我没有收到任何错误消息,但在模拟器中运行时,我得到了一堆没有任何内容的空单元格。 你知道我做错了吗?

经过多次测试后,似乎func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int两种方法都没有被调用,但我不知道我做错了什么

感谢adnvace

1 个答案:

答案 0 :(得分:2)

也许您忘了设置委托和数据源。您可以使用以下行在代码中执行此操作:

override func viewDidLoad() {
   super.viewDidLoad()

   self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")

   // Set delegate and datasource
   self.tableView.delegate = self
   self.tableView.dataSource = self
}