swift 3.0中的UITableView错误
Posted
技术标签:
【中文标题】swift 3.0中的UITableView错误【英文标题】:UITableView error in swift 3.0 【发布时间】:2016-06-21 14:12:15 【问题描述】:我刚刚将 Xcode 8 中的代码更新为 swift 3,并从我的 tableView 中得到以下错误:
2016-06-21 14:03:16.639567 Fibre[662:223131] * -[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] * 由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“UITableView (; layer = ; contentOffset: 0, 0; contentSize: 383, 88>) 未能从其 dataSource ()' 中获取单元格 *** 首先抛出调用堆栈: (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:以 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
有谁知道为什么会出现这些错误?
【问题讨论】:
【参考方案1】:你的func tableView(_tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell
行是错误的——你声明了一个函数,它的第一个参数是_tableView
,这意味着它实际上并没有提供返回单元格所需的协议函数。
将其更改为func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell
- 即放入一个空格!
【讨论】:
嗨!感谢您的回复,我编辑了该行,但仍然抛出相同的错误。 已排序!谢谢 cellForRowAt indexPath -> cellForRowAtIndexPath 谢谢【参考方案2】:这是 Swift 3 - XCode 8
的正确解决方案func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath)
return cell
【讨论】:
【参考方案3】:从 Swift 2 迁移到 Swift 3 all 表视图数据源和委托方法必须通过
将它们声明为私有并保留语法(不带任何下划线)
private func tableView(tableView : ...)
或使用新语法(见下划线后的空格字符)
func tableView(_ tableView : ...)
实际上,编译器应该显示有关该问题的警告以及如何修复它的建议。
【讨论】:
那么哪种方法被认为是正确的呢?添加 Private 还是将 _ 放入? 我会添加下划线。【参考方案4】:class offersViewController: UIViewController, UITableViewDelegate,UITableViewDataSource ....
您好像忘记添加“UITableViewDataSource”
【讨论】:
【参考方案5】:试试
func tableView(_ tableView: UITableView, cellForRowAt indexPath: NSIndexPath) -> UITableViewCell ...
【讨论】:
【参考方案6】:SWIFT 3.0.1 和 xcode 8.2 测试版
我也遇到同样的错误 下面会提到——
*** 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
在我声明表视图的数据源和委托后,它就可以工作了。
Correcway 如下所述。
class FamilyProfileViewController: UIViewController,UITableViewDataSource,UITableViewDelegate
variable declaration...
Function declaration...
【讨论】:
【参考方案7】:由于 swift 3 tableview 数据源和委托方法已更改,因此您的方法不满足 tableview 要求,正确的方法是:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
/*...*/
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
/*...*/
【讨论】:
以上是关于swift 3.0中的UITableView错误的主要内容,如果未能解决你的问题,请参考以下文章
UIViewController 内的 UITableView 没有响应(Swift 3.0)
Firebase 与 Swift 3.0 UITableView