如何使用代码连接dataSource和delegate - iOS Swift [英] How to connect dataSource and delegate with code - iOS Swift

查看:129
本文介绍了如何使用代码连接dataSource和delegate - iOS Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过拖放到viewController图标,当您通过Xcode中的UI进行连接时,我正在尝试更好地理解dataSource和委托出口如何连接到UITableView。

I'm trying to have a better understanding on how the dataSource and delegate outlets get connected to the UITableView under the hood when you do the connection through the UI in Xcode by dragging and dropping to the viewController icon.

我发现此主题但是我觉得我错过了一些东西,因为我无法使它工作。

I found this thread but I think I'm missing something because I cannot make it work.

这是我目前通过XCode连接插座工作正常的代码(通过拖放)。

Here is the code I currently have that works fine by connecting the outlets through XCode (by drag and dropping).

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

}

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

I tried removing the outlet connections made by XCode, created an outlet for the tableView (myTable) and added the following code in the viewDidLoad method but it doesn't work, no error it just doesn't load the data.

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

           myTable.delegate = self
           myTable.dataSource = self
        }

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

Can someone describe the steps needed to do this connection with code?

推荐答案

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

Just for reference here are the steps needed to do your connection programmatically.

1.-为tableView创建插座

1.- Create outlet for tableView

 @IBOutlet weak var myTable: UITableView!

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

2.- Assign delegate and dataSource in the viewDidLoad method.

myTable.delegate = self
myTable.dataSource = self

3.-完成

这篇关于如何使用代码连接dataSource和delegate - iOS Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆