我在MainstoryBoard
中有一個ViewController
。我添加了TableView
它。Swift:ViewController中的TableView
MainStoryBoard:
另外我有ViewController
類的外部的陣列,我想在陣列內的對象在TableView
中顯示。
我不知道該怎麼做。我連接TableView
和ViewController
之間的代表。
我在MainstoryBoard
中有一個ViewController
。我添加了TableView
它。Swift:ViewController中的TableView
MainStoryBoard:
另外我有ViewController
類的外部的陣列,我想在陣列內的對象在TableView
中顯示。
我不知道該怎麼做。我連接TableView
和ViewController
之間的代表。
在類聲明下面添加一個新的tableview實例變量。
@IBOutlet
var tableView: UITableView!
要符合UITableViewDelegate
和UITableViewDataSource
協議只是增加他們之間用逗號UIViewController
後的類聲明
之後,我們需要實現在ViewController
類tableView(_:numberOfRowsInSection:)
,tableView(_:cellForRowAtIndexPath:)
和tableView(_:didSelectRowAtIndexPath:)
方法和離開分離他們現在是空的
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
...
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0 // your number of cell 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
}
}
我認爲這是行得通的,但是當我到達我的do_table_refresh函數並調用:'self.tableView.reloadData()'時,它會因'致命錯誤而失敗:意外地在解包可選值時發現爲零# –
您需要在'viewDidLoad'方法中設置'self.tableView.delgate = self'和'self.tableView.dataSource = self'。 –
我可能會遲到,你可能已經修復了這一點。 你得到的錯誤是由於你的變量或常量返回一個零值。爲了測試這個,你可以爲它分配一個值(硬編碼它),並檢查完整的代碼是否工作,然後將其更改爲你的數組,不幸的是我做的東西程序化,不熟悉故事板。
如果你分享你的代碼,我們將協助你,如果這還沒有排序。
請參閱此鏈接http://www.ralfebert.de/tutorials/ios-swift-uitableviewcontroller/ https://www.weheartswift.com/how-to-make-a-simple-table-view-with -ios-8-and-swift/ –
@DharmeshDhorajiya很好,它的工作原理! 「weheartswift」有答案 – Eliko
歡迎任何時候@Eliko你這一切都是在谷歌罰款。 –