2017-08-01 60 views
0

我想在UIViewController裏面使用UITableView。但是,當我嘗試這麼做時,它會在啓動應用程序時給我一個錯誤。 錯誤說「法犯規從父覆蓋螞蟻法」UIViewController裏面的UITableView

import UIKit 

class GPATableViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { 

    struct Objects { 
     var sectionName : String! 
     var sectionObjects : [String]! 
    } 

    var objectsArray = [Objects]() 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     objectsArray = 
     [Objects(sectionName: "Section1" , sectionObjects: ["","",""]), 
     Objects(sectionName: "Section2" , sectionObjects: ["","",""]), 
     Objects(sectionName: "Section3" , sectionObjects: ["","",""])] 
    } 

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as UITableViewCell! 
     // cell?.textLabel!.text = objectsArray[indexPath.section].sectionObjects[indexPath.row] 

     print 
     return cell! 
    } 

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return objectsArray[section].sectionObjects.count 
    } 

    override func numberOfSections(in tableView: UITableView) -> Int { 
     return objectsArray.count 
    } 

    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { 
      return objectsArray[section].sectionName 
    } 

} 

回答

1

當你實現在UIViewControllerUITableViewDatasource,你是不是重寫方法。

從編譯器告訴你的方法中刪除override

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as UITableViewCell! 
    // cell?.textLabel!.text = objectsArray[indexPath.section].sectionObjects[indexPath.row] 

    print 
    return cell! 
} 

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return objectsArray[section].sectionObjects.count 
} 

func numberOfSections(in tableView: UITableView) -> Int { 
    return objectsArray.count 
} 

func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { 
     return objectsArray[section].sectionName 
} 

注:如果您使用的是UITableViewController,那麼你就需要override,這大概是什麼在你複製這個文件的任何事情。

+0

非常感謝你,你的回答也非常有幫助。還請注意,你把有用的..再次感謝! – Nawaf

1

涉及tableView的函數,如numberOfSections(...),cellForRowAt等不屬於UIViewController。它們屬於UITableViewDelegateUITableViewDataSource

要解決您的錯誤,請在這些功能前刪除override關鍵字。你不是在壓倒他們,而是根據協議的要求「實施」他們。

同時務必設置視圖控制器作爲delegatedataSource如果您尚未在故事板這樣做:

override func viewDidLoad() 
    super.viewDidLoad() 

    // other code... 

    tableView.delegate = self 
    tableView.dataSource = self 

    // other code... 
} 
+0

非常感謝。你的回答非常有幫助 – Nawaf