尝试将表格的值分配给self时,我收到以下错误。
Cannot assign a value of type 'ActivityViewController' to a value of
type 'UITableViewDataSource?'
以下代码行给出了上述错误。我已经查看了其他类似问题的SO,但没有找到表格视图。
class ActivityViewController: UIViewController, UITableViewDelegate, UITableViewDataSource
在我的viewDidLoad函数中
table.dataSource = self
完整代码:
class ActivityViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { // --> Error here
@IBOutlet var table: UITableView!
var likersArray = [PFObject]()
var username = ""
func refresh() {
var likersQuery = PFQuery(className: "Post")
likersArray.removeAll(keepCapacity: true)
likersQuery.orderByDescending("createdAt")
likersQuery.findObjectsInBackgroundWithBlock { (likers, error) -> Void in
if let likers = likers as? [PFObject] {
self.likersArray = likers
self.table.reloadData()
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
let myBarColor = UIColor(red: 48/256, green: 72/256, blue: 95/256, alpha: 1.0)
let view = UIView(frame: CGRect(x: 0.0, y: 0.0, width: UIScreen.mainScreen().bounds.size.width, height: 20.0))
view.backgroundColor = myBarColor
self.view.addSubview(view)
refresh()
table.dataSource = self // --> Error here
}
答案 0 :(得分:1)
您的代码存在两个问题,这就是我认为您收到这些错误的原因。首先,似乎存在一个支架问题。看起来你在刷新功能后关闭你的课程。不匹配的括号可能会导致各种奇怪的错误。
其次,您还需要遵守协议。 UITableViewDataSource协议指定了两个必需的函数。这些是numberOfRowsInSection和cellForRowAtIndexPath。毕竟,代码应该编译。这是我在操场上创建的代码版本。我的机器上一切都很好。请注意,我已删除了刷新功能,使事情变得简单。
class ActivityViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var table: UITableView!
var likersArray = [String]()
var username = ""
override func viewDidLoad() {
super.viewDidLoad()
let myBarColor = UIColor(red: 48/256, green: 72/256, blue: 95/256, alpha: 1.0)
let view = UIView(frame: CGRect(x: 0.0, y: 0.0, width: UIScreen.mainScreen().bounds.size.width, height: 20.0))
view.backgroundColor = myBarColor
self.view.addSubview(view)
table.dataSource = self
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return tableView.dequeueReusableCellWithIdentifier("CellName", forIndexPath: indexPath)
}
}
答案 1 :(得分:1)
此问题是因为ActivityViewController
未实现所需的数据源方法:numberOfRowsInSection
和cellForRowAtIndexPath
答案 2 :(得分:1)
仔细检查您的代理是否继承...我面临着同样的问题,因为编写UITabBarDelegate而不是UITableViewDelegate
答案 3 :(得分:0)
@ Welton122提供的答案应该是正确的答案,因为基本问题是原始UIViewController类声明中缺少UITableViewDelegate,UITableViewDataSource参数。