【问题标题】:Can not set UITableViewDataSouce and UITableViewDelegate to UIViewController无法将 UITableViewDataSouce 和 UITableViewDelegate 设置为 UIViewController
【发布时间】:2014-11-09 19:09:34
【问题描述】:

当我尝试将委托和数据源设置为 UIViewController 时,所有在 UITableViewController 中运行良好的函数都被检测为错误。

func numberOfSectionsInTableView(tableView: UITableView!) -> Int {
    // #warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1
}

func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete method implementation.
    // Return the number of rows in the section.
    return 10
}

错误是

FirstViewController.swift:11:1: Type 'FirstViewController' does not conform to protocol 'UITableViewDataSource':

UIKit.UITableViewDataSource:2:48: Protocol requires function      'tableView(_:numberOfRowsInSection:)' with type '(UITableView, numberOfRowsInSection: Int) -> Int'
FirstViewController.swift:29:10: Candidate has non-matching type '(UITableView!, numberOfRowsInSection: Int) -> Int'
UIKit.UITableViewDataSource:3:48: Protocol requires function 'tableView(_:cellForRowAtIndexPath:)' with type '(UITableView, cellForRowAtIndexPath: NSIndexPath) -> UITableViewCell'
FirstViewController.swift:29:10: Candidate has non-matching type '(UITableView!, numberOfRowsInSection: Int) -> Int'

这是 Xcode 6(不是测试版)。 UIViewController 中是否不再支持表格视图委托?

(相同的代码在 Xcode 6 Beta 5 中有效,但在 Xcode 6 GM 中无效。)

【问题讨论】:

    标签: xcode uitableview uiviewcontroller swift xcode6


    【解决方案1】:

    您正在使用implicitly unwrapped optionals (UITableView!)。但是这段代码不再使用可选项。

    方法签名现在如下所示:

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 0;
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0;
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        return UITableViewCell()
    }
    

    【讨论】:

    • 是的,我很傻,我在raywenderlich.com/76519/add-table-view-search-swift 找到了我的答案,...该死的苹果,他们改变了这个关键点而没有给我们打电话。谢谢亚伦,我接受你的回答
    • @DeckyFx 我认为他们确实在发行说明中告诉我们 :)
    • LOL 可能是,所以我可能错过了这个,他们应该让这个更改说明更明显
    【解决方案2】:

    对于 Xcode 6,要覆盖 UIViewController 中的委托函数,请使用:

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("CellID", forIndexPath: indexPath) as UITableViewCell
        // Configure the cell...
        return cell
    }
    

    【讨论】:

    • 只是几秒钟的不同^_^,无论如何谢谢艾哈迈德
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-20
    • 1970-01-01
    • 1970-01-01
    • 2014-10-30
    相关资源
    最近更新 更多