[英]Swift: TableView in ViewController
您在類聲明下方添加一個新的表視圖實例變量。
@IBOutlet weak var tableView: UITableView!
為了符合UITableViewDelegate
和UITableViewDataSource
協議,只需在類聲明中的UIViewController
之后添加以逗號分隔的它們
之后,我們需要在ViewController
類中實現tableView(_:numberOfRowsInSection:)
、 tableView(_:cellForRowAtIndexPath:)
和tableView(_:didSelectRowAtIndexPath:)
方法, ViewController
將它們留空
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
...
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0 // your number of cells here
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// your cell coding
return UITableViewCell()
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// cell selected code here
}
}
正如@ErikP 在評論中提到的,您還需要設置
self.tableView.delegate = self
self.tableView.dataSource = self
在viewDidLoad
方法中。
(或者在 Storyboard 中也很好用)。
我可能遲到了,你現在可能已經解決了這個問題。 您得到的錯誤是由於您的變量或常量返回 nil 值。 要對此進行測試,您可以為其分配一個值(對其進行硬編碼)並檢查完整代碼是否有效,然后將其更改為您的數組,不幸的是我以編程方式進行操作並且對故事板不太熟悉。
如果您分享您的代碼,如果尚未排序,我們將為您提供幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.