我试图更好地理解当您通过拖放到 viewController 图标通过 Xcode 中的 UI 进行连接时,数据源和委托插座如何在后台连接到 UITableView。
I found 这个线程 https://stackoverflow.com/questions/27022136/set-delegate-and-datasource-of-uitableview-programmatically-swif但我认为我错过了一些东西,因为我无法让它发挥作用。
这是我目前拥有的代码,通过 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
}
有人可以描述用代码进行此连接所需的步骤吗?