如何使用代码连接dataSource和delegate - iOS Swift

fs_*_*gre 7 datasource uitableview ios swift

我想通过拖放到viewController图标,通过Xcode中的UI进行连接,从而更好地了解dataSource和委托出口如何连接到UITableView.

我找到了这个帖子,但我觉得我错过了一些东西,因为我无法让它发挥作用.

这是我目前通过XCode连接出口(通过拖放)可以正常工作的代码.

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    var hobbies:[String] = ["Computers", "Photography", "Cars", "Reading", "Learning New Things"]


    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return hobbies.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as UITableViewCell

        cell.textLabel?.text =  hobbies[indexPath.row]

        return cell
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

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

}
Run Code Online (Sandbox Code Playgroud)

我尝试删除XCode创建的插座连接,为tableView(myTable)创建了一个插座,并在viewDidLoad方法中添加了以下代码,但它不起作用,没有错误,它只是不加载数据.

        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.

           myTable.delegate = self
           myTable.dataSource = self
        }
Run Code Online (Sandbox Code Playgroud)

有人能描述与代码建立连接所需的步骤吗?

fs_*_*gre 11

这里仅供参考,以编程方式进行连接所需的步骤.

1.-为tableView创建插座

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

2.-在viewDidLoad方法中分配delegate和dataSource.

myTable.delegate = self
myTable.dataSource = self
Run Code Online (Sandbox Code Playgroud)

3.-完成

  • 实际上,这可能是最常见的方式.选择你的表 - > Control - 将delegate和dataSource出口拖到viewController(黄色立方体).选择表后,您将在检查器中看到`delegate`和`dataSource`出口. (3认同)

Bru*_*pos 5

有几种方法可以做到这一点。

1.最简单的一种是通过拖放:

拖放

  • 在您的 main.storyboard 中选择您的 TableView;
  • 按下控制按钮;
  • 单击并将鼠标从 TableView 拖到 ViewController 的图标上并放下;
  • 然后选择数据源和委托,如上图所示。

2. 另一种方式是通过编码:

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

@IBOutlet weak var tableView: UITableView!

override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self
    }
}
Run Code Online (Sandbox Code Playgroud)

PS:确保不要忘记通过将 tableView 插座拖放到 ViewController 类中来将它连接到您的代码。

PPS:它还会要求您在类中实现以下方法,以便您的 tableView 正常工作:

  • 截面行数
  • cellForRowAtIndexPath

对于那些还没有它们的人,你会看到 Xcode 抱怨它。