如何使用代码连接dataSource和delegate – iOS Swift
我想通过拖放到viewController图标,通过Xcode中的UI进行连接,从而更好地了解dataSource和委托出口如何连接到UITableView。
我找到了这个post,但我觉得我错过了一些东西,因为我无法让它发挥作用。
这是我目前通过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. } }
我尝试删除XCode创建的sockets连接,为tableView( myTable
)创建了一个sockets,并在viewDidLoad
方法中添加了以下代码,但它不起作用,没有错误,它只是不加载数据。
override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. myTable.delegate = self myTable.dataSource = self }
有人可以描述与代码建立连接所需的步骤吗?
这里仅供参考,以编程方式进行连接所需的步骤。
1.-为tableView创建sockets
@IBOutlet weak var myTable: UITableView!
2.-在viewDidLoad方法中分配delegate和dataSource。
myTable.delegate = self myTable.dataSource = self
3.-完成
有几种方法可以做到这一点。
1.最简单的一种是拖放:
- 在你的main.storyboard中选择你的TableView;
- 按下控制按钮;
- 单击鼠标并将其从TableView拖动到ViewController的图标并将其删除;
- 然后选择dataSource和delegate,如上图所示。
2.另一种方式是编码:
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self } }
PS:确保不要忘记通过将tableView插槽拖放到ViewController类中来将其连接到代码中。
PPS:它还会要求您在类中实现以下方法,以便tableView正常工作:
- numberOfRowsInSection
- 的cellForRowAtIndexPath
对于那些还没有它们的人,你会看到Xcode抱怨它。