【发布时间】:2017-09-29 07:40:42
【问题描述】:
我正在尝试用其他方法更新 UITableviewcell 的标签。我还看到了很多关于 stackoverflow 的帖子,对我来说不是工作。我正在使用 Swift 3,我尝试了这个:
let indexPath = IndexPath.init(row: 0, section: 0)
let cell : CategoryRow = tableView.cellForRow(at: indexPath) as! CategoryRow
我收到了这个错误:
fatal error: unexpectedly found nil while unwrapping an Optional value
我在其他方法中使用它,我在 24 小时后更新 tableviewcell 标签文本。 代码在这里
var myQuoteArray = ["“If you have time to breathe you have time to meditate. You breathe when you walk. You breathe when you stand. You breathe when you lie down. – Ajahn Amaro”","We are what we repeatedly do. Excellence, therefore, is not an act but a habit. – Aristotle","The best way out is always through. – Robert Frost","“If you have time to breathe you have time to meditate. You breathe when you walk. You breathe when you stand. You breathe when you lie down. – Ajahn Amaro”","We are what we repeatedly do. Excellence, therefore, is not an act but a habit. – Aristotle","The best way out is always through. – Robert Frost"
]
func checkLastRetrieval(){
// let indexPath = IndexPath.init(row: 0, section: 0)
// let cell : CategoryRow = tableView.cellForRow(at: indexPath) as? CategoryRow
let indexPath = IndexPath.init(row: 0, section: 0)
guard let cell = tableView.cellForRow(at: indexPath) as? CategoryRow else { return }
print("Getting Error line 320")// This is not printing on console
let userDefaults = UserDefaults.standard
if let lastRetrieval = userDefaults.dictionary(forKey: "lastRetrieval") {
if let lastDate = lastRetrieval["date"] as? NSDate {
if let index = lastRetrieval["index"] as? Int {
if abs(lastDate.timeIntervalSinceNow) > 86400 { // seconds in 24 hours
// Time to change the label
var nextIndex = index + 1
// Check to see if next incremented index is out of bounds
if self.myQuoteArray.count <= nextIndex {
// Move index back to zero? Behavior up to you...
nextIndex = 0
}
cell?.quotationLabel.text = self.myQuoteArray[nextIndex]
let lastRetrieval : [NSObject : AnyObject] = [
"date" as NSObject : NSDate(),
"index" as NSObject : nextIndex as AnyObject
]
userDefaults.set(lastRetrieval, forKey: "lastRetrieval")
userDefaults.synchronize()
}
// Do nothing, not enough time has elapsed to change labels
}
}
} else {
// No dictionary found, show first quote
cell?.quotationLabel.text = self.myQuoteArray.first!
print("line 357")
// Make new dictionary and save to NSUserDefaults
let lastRetrieval : [NSObject : AnyObject] = [
"date" as NSObject : NSDate(),
"index" as NSObject : 0 as AnyObject
]
userDefaults.set(lastRetrieval, forKey: "lastRetrieval")
userDefaults.synchronize()
}
}
并在 ViewDidLoad() 中调用此方法
override func viewDidLoad() {
super.viewDidLoad()
checkLastRetrieval()
}
我该怎么办? 提前致谢
【问题讨论】:
-
使用 ? 使 CategoryRow 标签可选而不是!
-
我认为您正在更新单元格,而表格视图中没有单元格。
-
当您尝试这样做时,此单元格是否可见?
-
Nauman Malik,我已经做到了。但是没有用。
-
您的表格视图不会在
viewDidLoad中呈现,因此此时屏幕上不会有任何单元格。直到viewDidAppear,单元格才会出现在屏幕上。正如我在下面的评论中所说,正确的做法是更新表格的数据模型,以便在随后加载单元格时显示正确的数据。
标签: ios uitableview swift3