Подтвердить что ты не робот

IOS: "MyViewController" не соответствует протоколу "UITableViewDataSource"

  • Я новичок в разработке IOS swift. Раньше я работал с предыдущим Xcode 6 beta.

  • Я загрузил Xcode 6.0.1, и я не могу заставить это работать Xcode Version: 6.0.1

  • Я все еще получаю "MyViewController" не подтверждает протокол "UITableViewDataSource", когда я пытаюсь запустить пример.

Может кто-нибудь мне помочь? Я рассмотрел другие вопросы на этом сайте и добавил все необходимые функции для "UITableViewDataSource";


import UIKit
import Foundation

class MyViewController: UIViewController, UITableViewDelegate, UITableViewDataSource
{

var array1:[String] = ["one","two","three","four"]

    var array2:[String] = ["IOS","Android","java","c++","Swift"]

    let sectionCount = 2

    var myTableView:UITableView!

    //    init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
    //        var rect = CGRectMake(0, 0, 220, 320)
    //        myTableView = UITableView(frame: rect, style: UITableViewStyle.Grouped)
    //        super.init(nibName: nil, bundle: nil)
    //        // Custom initialization
    //    }

    override func viewDidLoad() {
        super.viewDidLoad()

        var rect = CGRectMake(0, 0, 320, 600)
        myTableView = UITableView(frame: rect, style: UITableViewStyle.Grouped)
        myTableView!.delegate = self
        myTableView!.dataSource = self
        self.view.addSubview(myTableView)

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    //dataSourrce
    //tableview:tableview,section:
    func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int{
        switch section{
        case 0:
            return array1.count
        case 1:
            return array2.count
        default:
            return 1
        }

    }


    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        //func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!{

        //---cellstart----
        let identifier = "identifier"
        //        var cell:UITableViewCell
        //cell
        var cell = tableView.dequeueReusableCellWithIdentifier(identifier) as? MyCell
        if cell == nil {
            //            cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: identifier)
            cell = MyCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: identifier)
        }
        //---cellend----

        switch indexPath.section{
        case 0:
            //            cell!.textLabel.text = array1[indexPath.row]
            cell!.myLable!.text = array1[indexPath.row]
        case 1:
            //            cell!.textLabel.text = array2[indexPath.row]
            cell!.myLable!.text = array2[indexPath.row]
        default:
            println()
        }
        var image = UIImage(named: "images/qq.png")
        //        cell!.imageView.image = image
        cell!.myImageView!.image = image
        //        cell!.detailTextLabel.text = "\(indexPath.section)\(indexPath.row)
        return cell!
    }

  //dataSourrce
    func numberOfSectionsInTableView(tableView: UITableView!) -> Int {
        return sectionCount
    }

    func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        var title:String? = nil
        switch section {
        case 0:
            title = "Num"
        case 1:
            title = "Prog"
        default:
            title = nil
        }
        return title
    }

    func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
        println("Test\(indexPath.section) \(indexPath.row)")
    }


    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 60.0
    }



    func numberOfComponentsInPickerView(pickerView: UIPickerView!) -> Int {}

    func pickerView(pickerView: UIPickerView!,numberOfRowsInComponent component: Int) -> Int{}

    func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController?{
    }

    func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController?{
    }

}

***************** Мой класс сотовой связи *************************** ********

import Foundation
import UIKit

class MyCell: UITableViewCell {

    let indetifier:String = "indetifier"


    var myLable:UILabel?


    var myImageView:UIImageView?

        override init(style: UITableViewCellStyle, reuseIdentifier: String!)
        {
        super.init(style: .Subtitle, reuseIdentifier: indetifier)

        var rect = CGRectMake(10, 0, 60, 30)
        self.myLable = UILabel()
        self.myLable!.frame = rect
        self.myLable!.textColor = UIColor.redColor()
        self.contentView.addSubview(self.myLable!)

        var imageRect = CGRectMake(160, 10, 40, 40)
        self.myImageView = UIImageView()
        self.myImageView!.frame = imageRect
        self.contentView.addSubview(self.myImageView!)


    }

        required init(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
}
4b9b3361

Ответ 1

Вам нужно посмотреть на все сообщение об ошибке. Это конкретное сообщение включает в себя дополнительную информацию о том, какие методы отсутствуют:

Type 'MyViewController' does not conform to protocol 'UITableViewDataSource'
Protocol requires function 'tableView(_:numberOfRowsInSection:)' with type '(UITableView, numberOfRowsInSection: Int) -> Int'
Candidate has non-matching type '(UITableView!, numberOfRowsInSection: Int) -> Int'

Итак... ваш numberOfRowsInSection принимает необязательный UITableView и должен принимать требуемый UITableView (это изменение, которое они сделали между 6 и 6.1, все методы делегата и источника данных UITableView теперь принимают требуемые значения tableView и indexPath)

Ответ 2

Попробуйте это простое решение:

import UIKit

class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource
{
    //MARK: - Life Cycle
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    //MARK: - Tableview Delegate & Datasource
    func tableView(tableView:UITableView, numberOfRowsInSection section:Int) -> Int
    {
        return 10
    }

    func numberOfSectionsInTableView(tableView: UITableView) -> Int
    {
        return 1
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {

        let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "MyTestCell")
        return cell
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {

    }

}

Ответ 3

class ROTableView: UITableView, UITableViewDelegate {

    func tableView(tableView:UITableView!, numberOfRowsInSection section:Int) -> Int {
        return 10
    }

    func tableView(tableView:UITableView!, cellForRowAtIndexPath indexPath:NSIndexPath!) -> UITableViewCell! {
        let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "MyTestCell")

//        cell.text = "Row #\(indexPath.row)"
//        cell.detailTextLabel.text = "Subtitle #\(indexPath.row)"

        return cell
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    }
}

При создании подкласса для UITableView см. приведенный выше код, вы не получите никаких ошибок.

Ответ 4

В моем случае я назвал свой UITableView как tableView. Это вызвало ту же ошибку:

"MyViewController" не соответствует протоколу "UITableViewDataSource"

в том числе другая ошибка:

Кандидат не является функцией

И изменил имя tableview на что-то другое, ошибка исчезла.

Ответ 5

Для меня удаление UITableViewDataSource из списка унаследованных классов устраняет проблему