【发布时间】:2016-02-15 03:12:04
【问题描述】:
当您通过 Xcode 中的 UI 通过拖放到 viewController 图标进行连接时,我试图更好地了解 dataSource 和委托出口如何连接到引擎盖下的 UITableView。
我找到了this thread,但我认为我错过了一些东西,因为我无法让它工作。
这是我目前拥有的代码,通过 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 建立的出口连接,为 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
}
有人可以描述用代码进行这种连接所需的步骤吗?
【问题讨论】:
-
你检查
myTable插座连接了吗? -
好吧,我实际上是通过将 tableView 拖放到 viewController 来创建插座的。如果正确理解这一点,我上面描述的过程应该可以工作,对吗?
Step 1.- Create outlet for tableViewStep 2._ Add assign delegate and dataSource in the viewDidLoad method.DONE -
是的,听起来不错。您可能只需要致电
reloadData -
我会试试看会发生什么。感谢您的确认。
-
它现在可以工作了,我不确定我错过了什么。非常感谢@Wain。
标签: ios swift uitableview datasource