Swift: My custom UITableViewDataSource class thinks it does not conform to 'UITableViewDataSource' protocol
I checked a few more questions, the answers to which seem to be in the method declarations of the data source. However, I cannot find what is wrong with my method 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 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's wrong?
source to share
As the error message indicates, the protocol requires the table view data source methods to be "Objective-C compatible". This can be achieved with
-
so that your class inherits from
NSObject
(or any subclassNSObject
)class GuestControl: NSObject, ...
-
or adding an attribute
@objc
to the class definition@objc class GuestControl: ...
-
or adding attribute
@objc
to data source methods@objc func tableView(tableView: UITableView, numberOfRowsInSection section: Int) ...
In the first two cases, all methods of the class are executed by Objective-C compatible.
If a view controller (tables) is used as the data source for a table view, this is automatically done because it UI(Table)ViewController
inherits from NSObject
.
source to share