如果我遵循此https://3v4l.org/8SSsN的建议并且使用DispatchQueue在主线程中调用reloadData(),则我的UITableView将仅显示单元格中的所有完全加载的内容。我在tableView cellForRowAt中执行此操作,因为它不会将我的数组中的值完全加载到所有单元格中。现在它不断重装,显然是非常耗能的。这使得在表视图中滚动更加困难,这是有道理的。
如何在我仍然需要的情况下将数据加载到单元格中时,如何防止这种荒谬的能量使用?
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell:UITableViewCell? =
charitiesSupportedTable?.dequeueReusableCell(withIdentifier: "SupportedCell")
if (cell == nil)
{
cell = UITableViewCell(style: UITableViewCellStyle.subtitle,
reuseIdentifier: "abc")
}
if(indexPath.row <= moneyRaisedOfPrevPostsArray.count-1){
cell?.textLabel?.text = charOfPrevPostsArray[indexPath.row]
cell?.detailTextLabel?.text = moneyRaisedOfPrevPostsArray[indexPath.row]
}
DispatchQueue.main.async {
self.charitiesSupportedTable.reloadData()
}
return cell!
}
这是我创建数组
的viewDidLoadoverride func viewDidLoad() {
super.viewDidLoad()
let userEmail = Auth.auth().currentUser!.email
var email1 = userEmail?.replacingOccurrences(of: "@", with: "", options: NSString.CompareOptions.literal, range:nil)
email1 = email1?.replacingOccurrences(of: ".", with: "", options: NSString.CompareOptions.literal, range:nil)
charitiesSupportedTable.delegate = self
charitiesSupportedTable.dataSource = self
charitiesSupportedTable.isScrollEnabled = false
reff = Database.database().reference().child("Posts")
let userRef1 = reff?.queryOrdered(byChild: "user").queryEqual(toValue : email1)
userRef1?.observe(.value, with: { (snapshot) in
for child in snapshot.children {
let snap = child as! DataSnapshot
let key = snap.key
let value = snap.value
let valueAsDict = value as! NSDictionary
charityOfPrevPosts = valueAsDict.value(forKey: "charity") as! String
viewCountOfPrevPosts = valueAsDict.value(forKey: "viewCount") as! String // times .006
moneyRaisedPrevPosts = Double(viewCountOfPrevPosts)! * 0.006
charOfPrevPostsArray.append(charityOfPrevPosts)
moneyRaisedOfPrevPostsArray.append(String(moneyRaisedPrevPosts))
}
charOfPrevPostsArray.reverse()
moneyRaisedOfPrevPostsArray.reverse()
}
)
moneyRaisedOfPrevPostsArray.removeAll()
charOfPrevPostsArray.removeAll()
reff = Database.database().reference().child("UsersViews").child(email1!).child("totalMoneyRaised")
reff?.observe(DataEventType.value, with: { (snapshot) in
var totalMoney = snapshot.value as! Double
self.totalMoneyLabel.text = String(format: "$%.02f", totalMoney)
})
// don't know if this part is relevant but I do return charitiesCount + 2 in numberOfRowsInSection
reff = Database.database().reference()
databaseHandle = reff?.child("UsersViews").child(email1!).child("charitiesSupported").observe(.value, with: { (snapshot) in
let myDictionary11 = snapshot.value as? NSDictionary
// Adds brands and charities to myData array
for value in (myDictionary11?.allValues)! {
self.myCharities.append(value as! String)
}
charitiesCount = self.myCharities.count
})
}