I have checked a few other questions out there, of which the answers seem to be in the datasource methods' declarations. However, I cannot find what's wrong with my methods declarations.
Here is my class:
import UIKit
class GuestControl: UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var leftTable: UITableView!
@IBOutlet weak var rightTable: UITableView!
var userList = [User]() //even numbers including 0 go on the left table, odd numbers go on the
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//Here is where we link to that user's contact page
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: GuestTableViewCell = tableView.dequeueReusableCellWithIdentifier("guestCell") as! GuestTableViewCell
if tableView == leftTable {
cell.configureCellWithUser(userList[indexPath.row+indexPath.row])
} else {
cell.configureCellWithUser(userList[indexPath.row+indexPath.row+1])
}
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let num = Double(userList.count) / 2.0
if tableView == leftTable {
return Int(round(num)) //round up
} else {
return Int(num) //round down
}
}
}
And here is the exact error:
Protocol requires function 'tableView(_:numberOfRowsInSection:)' with type '(UITableView, numberOfRowsInSection: Int) -> Int'
Candidate is not '@objc', but protocol requires it
Protocol requires function 'tableView(_:cellForRowAtIndexPath:)' with type '(UITableView, cellForRowAtIndexPath: NSIndexPath) -> UITableViewCell'
Candidate is not '@objc', but protocol requires it
What is wrong?
答案 0 :(得分:6)
As the error message indicates, the protocol requires that the table view data source methods are "Objective-C compatible". This can be achieved by
making your class inherit from NSObject
(or any NSObject
subclass)
class GuestControl: NSObject, ...
or adding the @objc
attribute to the class definition
@objc class GuestControl: ...
or adding the @objc
attribute to the data source methods
@objc func tableView(tableView: UITableView, numberOfRowsInSection section: Int) ...
In the first two cases, all methods of the class are made Objective-C compatible.
If a (table) view controller is used as the table view data source then this automatically satisfied because UI(Table)ViewController
inherits
from NSObject
.