2014-10-09 44 views
1

我正在學習,並迅速在一個類中的以下方法:如何調用兩次方法?

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    // Return the number of rows in the section. 
    return countries.count 
} 
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as UITableViewCell 
    cell.textLabel!.text = countries[indexPath.row] 
    return cell 
} 

這是令人費解給我,因爲我沒有在那裏我可以有一個方法(即的tableView),可稱爲前兩次編程。這怎麼可能?

+2

你說的叫了兩聲是什麼意思?你想調用兩次方法?或者是因爲'tableView:cellForRowAtIndexPath:'被調用兩次?它每次需要時都會調用,就像任何時候必須顯示單元格一樣。 – Larme 2014-10-09 13:22:20

+0

那麼,tableView會出現兩次方法。我不明白這是怎麼可能的。如果我創建一個名爲myFunc的函數,我不能創建另一個名爲myFunc的函數嗎? – SimonRH 2014-10-09 13:28:26

+0

那麼,以某種方式,你可以。如果你轉換到Objective-C,因爲我不熟悉Swift,你有兩個方法:'tableView:numberOfRowsInSection:'和'tableView:cellForRowAtIndexPath:'。所以他們不一樣。這只是Swift的聲明方式,如果不是,你可能會引誘你使用相同的方法。 – Larme 2014-10-09 13:32:14

回答

4

您不應該將該方法視爲僅由括號前的名稱定義。如果參數不同,那麼它是完全不同的方法。

1

這些不是方法調用;這些是函數定義。但是,由於它們共享相同的函數名稱,因此不能在未指定參數名稱的情況下調用它們。調用他們會爲這樣做(儘管它在UITableView內部完成的,所以你不必擔心它在這種特殊情況下):

tableView(theTableView, numberOfRowsInSection:theSection); 
tableView(theTableView, cellForRowAtIndexPath:theIndexPath); 

注意sectionindexPath是由內部使用的名稱功能分別爲外部參數名稱numberOfRowsInSectioncellForRowAtIndexPath

有關函數名,參數的更多信息,並簽名的總體結構,是指雨燕文檔瀏覽:https://developer.apple.com/library/ios/documentation/swift/conceptual/swift_programming_language/Declarations.html#//apple_ref/doc/uid/TP40014097-CH34-XID_598