Swift:ViewController中的TableView

Eli*_*iko 27 iphone xcode uitableview ios swift

我有一个ViewControllerMainstoryBoard.我添加了TableView 它.

MainStoryBoard:

在此输入图像描述

另外我在ViewController类之外有一个数组,我希望数组中的对象显示在TableView.

我无法弄清楚该怎么做.我在TableView和之间连接了代理ViewController.

Dha*_*iya 49

您在类声明下添加一个新的tableview实例变量.

@IBOutlet weak var tableView: UITableView!
Run Code Online (Sandbox Code Playgroud)

为了符合UITableViewDelegateUITableViewDataSource协议,只需UIViewController在类声明中添加逗号后用逗号分隔

之后,我们需要实现tableView(_:numberOfRowsInSection:),tableView(_:cellForRowAtIndexPath:)tableView(_:didSelectRowAtIndexPath:)在方法ViewController类,并让他们空,现在

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    ...

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0 // your number of cells here
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        // your cell coding 
        return UITableViewCell()
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        // cell selected code here
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 您将需要在`viewDidLoad`方法中设置`self.tableView.delgate = self`和`self.tableView.dataSource = self`。 (5认同)
  • 在你的故事板中,不要忘记从表格视图拖动到视图控制器顶部的黄色圆圈。放手并选择“数据源”。再次执行此操作,但选择委托。 (2认同)