UITableViewDataSource
協議定義了UITableView
需要用數據填充自己的方法。它定義了幾種可選的方法,但是有兩點是需要(不可選):
// this method is the one that creates and configures the cell that will be
// displayed at the specified indexPath
– tableView:cellForRowAtIndexPath:
// this method tells the UITableView how many rows are present in the specified section
– tableView:numberOfRowsInSection:
而且,不需要下面的方法,但也是一個好主意來實現(數據源的一部分太)
現在
// this method tells the UITableView how many sections the table view will have. It's a good idea to implement this method even if you just return 1
– numberOfSectionsInTableView:
,該方法–tableView:cellForRowAtIndexPath:
會在你UITableView
運行一次,每可見細胞。例如,如果您的數據數組有10個元素,但只有5個可見,則–tableView:cellForRowAtIndexPath:
將運行5次。當用戶向上或向下滾動時,將再次調用每個可見單元格的方法。
你說什麼:「(該)數據源方法已經運行了10次以獲得行數。」是不正確的。數據源方法–tableView:numberOfRowsInSection:
不運行10次以獲取行數。實際上這個方法只運行一次。此外,此方法在–tableView:cellForRowAtIndexPath:
之前運行,因爲表視圖需要知道它必須顯示多少行。
最後,方法–numberOfSectionsInTableView:
也運行一次,並且它在–tableView:numberOfRowsInSection:
之前運行,因爲表視圖需要知道段將如何存在。請注意這種方法不是必需的。如果你沒有實現它,表格視圖將假定只有一個部分。
現在我們可以將注意力集中在UITableViewDelegate
協議上。該協議定義了與UITableView
實際交互的方法。例如,它定義了管理單元格選擇的方法(例如,當用戶點擊一個單元格時),單元格編輯(插入,刪除,編輯等),配置頁眉和頁腳(每個部分可以有頁眉和頁腳), UITableViewDelegate
中定義的所有方法都是可選的。實際上,你根本不需要實現UITableViewDelegate
以獲得表視圖的正確基本行爲,即顯示單元格。
一些的UITableViewDelegate
最常用的方法是:
// If you want to modify the height of your cells, this is the method to implement
– tableView:heightForRowAtIndexPath:
// In this method you specify what to do when a cell is selected (tapped)
– tableView:didSelectRowAtIndexPath:
// In this method you create and configure the view that will be used as header for
// a particular section
– tableView:viewForHeaderInSection:
希望這有助於!
我認爲你使用術語_data源method_和_delegate method_錯誤。你正在討論的兩種方法都是_data source_('')的一部分。這兩件事情是分裂的:_data source_提供數據,_delegate_提供行爲(對事件作出反應等)。通常都是使用_one_類實現的,所以它們經常混合在一起。 –
Tricertops