2014-10-09 43 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