swift 3.0 中的 UITableView 错误

UITableView error in swift 3.0

我刚刚将 Xcode 8 中的代码更新为 swift 3,并从我的 tableView 中得到以下错误:

2016-06-21 14:03:16.639567 Fibre[662:223131] * Assertion failure in -[UITableView _configureCellForDisplay:forIndexPath:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit/UIKit-3575.10/UITableView.m:7964 2016-06-21 14:03:16.641663 Fibre[662:223131] * Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView (; layer = ; contentOffset: {0, 0}; contentSize: {383, 88}>) failed to obtain a cell from its dataSource ()' *** First throw call stack: (0x1831e5980 0x1827e04bc 0x1831e5854 0x183c09c84 0x1890b065c 0x1892ae2bc 0x1892ae3c0 0x18929c924 0x1892b3084 0x18905340c 0x188f6c58c 0x186490d6c 0x186485aac 0x18648596c 0x1864054fc 0x18642c7c4 0x18642d148 0x183195954 0x183193584 0x183193a14 0x1830c62e4 0x184a9f15c 0x188fda6fc 0x188fd5438 0x100070c3c 0x182c68600) libc++abi.dylib: terminating with uncaught exception of type NSException

我正在使用 xib 和以下代码:

import Foundation
import Parse
import UIKit


extension UIImageView {
public func imageFromUrl(_ urlString: String) {
    if let url = URL(string: urlString) {
        let request = URLRequest(url: url)
        NSURLConnection.sendAsynchronousRequest(request, queue: OperationQueue.main()) {
            (response: URLResponse?, data: Data?, error: NSError?) -> Void in
            if let imageData = data as Data? {
                self.image = UIImage(data: imageData)
            }
        }
    }
}
}

class offersViewController: UIViewController, UITableViewDelegate {




@IBOutlet weak var tableView: UITableView!

@IBOutlet weak var offersView: UIView!


@IBOutlet weak var offerTitleLabel: UILabel!

@IBOutlet weak var smartCode: UILabel!

@IBOutlet weak var customerName: UILabel!


 @IBAction func closeButton(sender: AnyObject) {

    offersView.isHidden = true
}



var array: [String] = [String]()
var arrayImages: [String] = [String]()

override func viewDidLoad(){
    super.viewDidLoad()




}


override func viewDidAppear(_ animated: Bool) {

    self.array.removeAll(keepingCapacity: true)
    self.arrayImages.removeAll(keepingCapacity: true)

    let nib = UINib(nibName: "vwTblCell", bundle: nil)
    tableView.register(nib, forCellReuseIdentifier: "cell")


    let date = Date()
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "EEEE"
    let weekDay = dateFormatter.string(from: date)

    print(weekDay)

    tableView.isHidden = true




    let query = PFQuery(className:"offers")
    query.whereKey("day", equalTo:"\(weekDay)")



    query.findObjectsInBackground {
        (objects: [PFObject]?, error: NSError?) -> Void in

        if error == nil {
            // The find succeeded.
            print("Successfully retrieved \(objects!.count) scores.")
            // Do something with the found objects
            if let objects = objects {


                let birthdayOffer = "£25 free credit on your Birthday!"
                let birthdayOfferImage = "birthday"

                self.array.append(birthdayOffer as String)
                print(self.array)

                self.arrayImages.append(birthdayOfferImage as String)
                print(self.arrayImages)


                for object in objects {



                    let query = PFQuery(className:"offers")
                    query.getObjectInBackground(withId: "\(object.objectId!)"){
                        (gameScore: PFObject?, error: NSError?) -> Void in
                        if error == nil && gameScore != nil {
                            let offertitle = gameScore!["offertitle"] as! String
                            let offerImage = gameScore!["imagename"] as! String

                            // Add birthday to array



                            self.array.append(offertitle as String)
                            print(self.array)

                            self.arrayImages.append(offerImage as String)
                            print(self.arrayImages)


                        }



                        self.tableView.reloadData()
                        self.tableView.isHidden = false
                    }



                }


            }


        }



    }








}







   func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {


    return array.count


    }

var cell : UITableViewCell?

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



        let cell: TblCell = self.tableView.dequeueReusableCell(withIdentifier: "cell",for: indexPath) as! TblCell


        let url = URL(string: "https://checkmyweave.co.uk/\(arrayImages[(indexPath as NSIndexPath).row]).png")
        cell.offerImage.sd_setImage(with: url)




               cell.offerTitleLabel.text = self.array[(indexPath as NSIndexPath).row]


        let defaults = UserDefaults.standard()






        let userID = defaults.string(forKey: "userID")!



        let query = PFQuery(className:"members")
        query.getObjectInBackground(withId: "\(userID)") {
            (gameScore: PFObject?, error: NSError?) -> Void in
            if error == nil && gameScore != nil {

                let smartCode = gameScore!["smartcode"] as! String

                let defaults = UserDefaults.standard()




                let userName = defaults.string(forKey: "userName")!

        self.smartCode.text = smartCode
        self.customerName.text = userName




            } else {
                print(error)
            }
        }


        return cell




}




 func numberOfSectionsIntableView(_tableView: UITableView) -> Int {

    return 1
}

private func tableView(_tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print((indexPath as NSIndexPath).row)


    let date = Date()
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "EEEE"
    let weekDay = dateFormatter.string(from: date)

    offerTitleLabel.text = self.array[(indexPath as NSIndexPath).row]


    offersView.isHidden = false
    print(offerTitleLabel.text)
    let query = PFQuery(className:"offers")
    query.whereKey("offertitle", equalTo:"\(offerTitleLabel.text!)")
    query.whereKey("day", equalTo:"\(weekDay)")

    query.findObjectsInBackground {
        (objects: [PFObject]?, error: NSError?) -> Void in

        if error == nil {
            // The find succeeded.
            print("Successfully retrieved \(objects!.count) scores.")
            // Do something with the found objects
            if let objects = objects {
                for object in objects {



                    let query = PFQuery(className:"offers")
                    query.getObjectInBackground(withId: "\(object.objectId!)"){
                        (gameScore: PFObject?, error: NSError?) -> Void in
                        if error == nil && gameScore != nil {
                            let offerdesc = gameScore!["offerDesc"] as! String

                            print(offerdesc)




                        }}}}}}
}


 private func tableView(_tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 140
}



}

有谁知道为什么会出现这些错误?

你的行 func tableView(_tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell { 是错误的 - 你正在声明一个函数,它的第一个参数是 _tableView,这意味着它实际上并没有提供返回单元格所需的协议函数。

将其更改为 func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell { - 即输入 space!

从 Swift 2 迁移到 Swift 3 时 all table 必须通过 [=12] 更改视图数据源和委托方法=]

  • 将它们声明为私有并保留语法(没有任何下划线)

    private func tableView(tableView : ...)
    
  • 或使用新语法(见下划线后的space字符)

    func tableView(_ tableView : ...)
    

实际上,编译器应该显示有关该问题的警告以及如何修复它的建议。

尝试

func tableView(_ tableView: UITableView, cellForRowAt indexPath: NSIndexPath) -> UITableViewCell {...}

这是 Swift 3 - XCode 8

的正确解法
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath)
    return cell
}
class offersViewController: UIViewController, UITableViewDelegate,UITableViewDataSource { .... }

你好像忘了添加 "UITableViewDataSource"

SWIFT 3.0.1 和 xcode 8.2 Beta

我也遇到同样的错误 如下所述--

*** Assertion failure in 
-[UITableView         _configureCellForDisplay:forIndexPath:],     /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit/UIKit-    3599.6.1/UITableView.m:8035
    2016-11-24 12:20:59.578026 JJS Connect[1479:587032] *** Terminating app    due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView  <UITableView: 0x1010c7400; frame = (0 277; 375 390); clipsToBounds = YES; autoresize = RM+BM; gestureRecognizers = <NSArray: 0x17005b9f0>; layer = <CALayer: 0x17022d680>; contentOffset: {0, 0}; contentSize: {375, 176}>) failed to obtain a cell from its dataSource (<JJS_Connect.FamilyProfileViewController: 0x100f41660>)'

*** First throw call stack:

我忘记在 Class 文件中声明协议 - UITableViewDataSource,UITableViewDelegate

在我声明 Table 视图的数据源和委托后,它正在工作。

下面提到了Correcway。

class FamilyProfileViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {

variable declaration...
Function declaration...

}

如swift 3 tableview 数据源和委托方法已更改,因此您的方法不满足 tableview 要求,正确的方法是:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
    /*...*/
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
    /*...*/
}