TableView 数据滞后
TableView gets laggy with data
所以我遇到了问题
table 视图在 reloading/adding 行几次后变慢(对滚动、点击的响应变慢)
所以用户登录后,应用下载10"WorldMessages"。它已加载到此 table 视图中。
如果用户向下滚动,它会调用一个加载更多 10 的函数:loadOlderOwnWorldMessages()
每个单元格都有一个 tapGestureRecognizer
+ longPressGestureRecognizer
而且我不得不提一下,如果用户重新加载 tableView,那么它会清除数据并再次仅加载前 10 个 WorldMessages
问题
我不知道为什么,但是例如,如果我重新加载 tableView 50 次并且每次我向下滚动一点或更多,然后 tableView 变慢.
可能是因为 tap/long 按下手势识别器或限制?
应用程序如下所示:
视频卡顿后:
https://www.youtube.com/watch?v=65NkjS-Kz3M
(如果我关闭应用程序并再次打开它,它会再次正常运行,直到我重新加载它几次)
代码:
// 这不是全部代码,我删除了很多不重要的行(比如重新加载函数等)
class ProfileViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITabBarDelegate {
// Classes
let handleData = HandleData()
let handleResponses = HandleResponses()
let worldMessagesFunctions = WorldMessagesFunctions()
let profileFunctions = ProfileFunctions()
// View Objects
@IBOutlet var tableView : UITableView!
// Variables
var userWorldMessages = [WorldMessage]()
var lastContentOffsetY : CGFloat?
var currentSelectedWorldMessageIndexPath : IndexPath?
// Main Code
override func viewDidLoad() {
super.viewDidLoad()
userWorldMessages = ownWorldMessages.shared.worldMessages
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return userWorldMessages.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ProfileWorldMessageCell", for: indexPath) as! ProfileWorldMessageCell
let worldMessage = userWorldMessages[indexPath.row]
cell.worldMessageData = worldMessage
cell.messageLabel.text = worldMessage.message
if let image = UIImage(named: "bubble") {
let h = image.size.height / 2
let w = image.size.width / 2
cell.bubbleImageView.image = image
.resizableImage(withCapInsets:
UIEdgeInsetsMake(h, w, h, w),
resizingMode: .stretch).withRenderingMode(.alwaysTemplate)
cell.bubbleImageView.tintColor = appColors.worldMessageBubble
}
let calendar = NSCalendar.current
let date = Date(timeIntervalSince1970: Double(worldMessage.leftTime))
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US")
var dateFormat = "yyyy MMM dd"
if calendar.isDateInToday(date) {
// Today
dateFormat = "HH:mm"
dateFormatter.string(from: date)
} else if (calendar.date(byAdding: .weekOfYear, value: -1, to: Date())! < date){
// This last 7 days
dateFormat = "EEEE HH:mm"
} else if (calendar.date(byAdding: .month, value: -12, to: Date())! < date){
// This year
dateFormat = "MMM dd"
} else {
dateFormat = "yyyy MMM dd"
}
dateFormatter.dateFormat = dateFormat
let strDate = dateFormatter.string(from: date)
cell.timeLabel.text = strDate
cell.commentsButton.setTitle("\(worldMessage.comments!) comments", for: .normal)
cell.likesButton.setTitle("\(worldMessage.likes!) likes", for: .normal)
// tapped
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(bubbleTappedHandler))
cell.bubbleButton.addGestureRecognizer(tapGestureRecognizer)
cell.bubbleButton.isUserInteractionEnabled = true
// long pressed
let longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(bubbleLongPressHandler))
longPressGestureRecognizer.minimumPressDuration = 0.5
cell.addGestureRecognizer(longPressGestureRecognizer)
cell.isUserInteractionEnabled = true
return cell
}
var cellHeights: [IndexPath : CGFloat] = [:]
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cellHeights[indexPath] = cell.frame.size.height
if indexPath.row == UserWorldMessagesStore.shared.worldMessages.count - 1 && userWorldMessagesCanLoadMore == true {
loadOlderOwnWorldMessages()
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
if cellHeights[indexPath] != nil {
return CGFloat(Float(cellHeights[indexPath] ?? 0.0))
}
else {
return UITableViewAutomaticDimension
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if (lastContentOffsetY != nil){
tableView.setContentOffset(CGPoint(x: 0, y: lastContentOffsetY!), animated: false)
}
}
func loadOlderOwnWorldMessages(){
profileFunctions.loadOlderOwnWorldMessages(startIndex: (userWorldMessages.count)) { response, newUserWorldMessages in
if let response = response {
if response.type == 1 {
DispatchQueue.main.async(execute: {() -> Void in
if newUserWorldMessages != nil {
var insertRows : [IndexPath] = []
var fromIndex = UserWorldMessagesStore.shared.worldMessages.count - 1
for worldMessage in newUserWorldMessages! {
UserWorldMessagesStore.shared.worldMessages.append(worldMessage)
insertRows.append(IndexPath(row: fromIndex, section: 1))
fromIndex += 1
}
self.userWorldMessages = UserWorldMessagesStore.shared.worldMessages
self.tableView.beginUpdates()
self.tableView.insertRows(at: insertRows, with: .automatic)
self.tableView.endUpdates()
}
})
} else {
DispatchQueue.main.async(execute: {() -> Void in
self.handleResponses.displayError(title: response.title, message: response.message)
})
}
}
}
}
@objc func bubbleTappedHandler(sender: UITapGestureRecognizer, should: Bool) {
let touchPoint = sender.location(in: self.tableView)
if let indexPath = tableView.indexPathForRow(at: touchPoint) {
if indexPath == currentSelectedWorldMessageIndexPath {
// it was already selected, so deselect it
deselectCurrentSelectedWorldMessage()
} else {
// select new one, deselect old one if was selected
if (currentSelectedWorldMessageIndexPath != nil){
deselectCurrentSelectedWorldMessage()
}
selectWorldMessage(indexPath: indexPath)
}
}
}
func selectWorldMessage(indexPath: IndexPath) {
tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none)
currentSelectedWorldMessageIndexPath = indexPath
if let cell = tableView.cellForRow(at: indexPath) as? ProfileWorldMessageCell {
// Change some constraints
cell.messageLabelTopConstraint.constant = 14
cell.messageLabelBottomConstraint.constant = 14
UIView.animate(withDuration: 0.15, animations: {
self.view.layoutIfNeeded()
self.tableView.beginUpdates()
self.tableView.endUpdates()
}, completion: nil)
}
}
@objc func deselectCurrentSelectedWorldMessage(){
UIMenuController.shared.setMenuVisible(false, animated: true)
if (currentSelectedWorldMessageIndexPath == nil){
return
}
let indexPath = currentSelectedWorldMessageIndexPath!
if let cell = tableView.cellForRow(at: indexPath) as? ProfileWorldMessageCell {
// Change back some constraints
cell.messageLabelTopConstraint.constant = 10
cell.messageLabelBottomConstraint.constant = 10
UIView.animate(withDuration: 0.15, animations: {
self.view.layoutIfNeeded()
self.tableView.beginUpdates()
self.tableView.endUpdates()
}, completion: nil)
}
currentSelectedWorldMessageIndexPath = nil
}
@objc func bubbleLongPressHandler(sender: UILongPressGestureRecognizer, should: Bool) {
// Show options like copy, delete etc.
}
}
您的 cellForRow
函数有几处 非常 错误:
- 细胞被重复使用,而您忽略了这一事实。每次调用
cellForRow
时,您都在创建手势识别器的新实例,并且在重复使用单元格时,您正在添加另一个。这意味着如果你的单元格被重复使用了 50 次,它将添加 50 个手势识别器。您应该只创建一次手势识别器
- 你每次创建一个
DateFormatter
并设置它的 dateFormat
属性,这实际上是一个非常昂贵的过程。相反,您应该为每个日期格式都有一个格式化程序的静态实例
所以我遇到了问题
table 视图在 reloading/adding 行几次后变慢(对滚动、点击的响应变慢)
所以用户登录后,应用下载10"WorldMessages"。它已加载到此 table 视图中。
如果用户向下滚动,它会调用一个加载更多 10 的函数:loadOlderOwnWorldMessages()
每个单元格都有一个 tapGestureRecognizer
+ longPressGestureRecognizer
而且我不得不提一下,如果用户重新加载 tableView,那么它会清除数据并再次仅加载前 10 个 WorldMessages
问题
我不知道为什么,但是例如,如果我重新加载 tableView 50 次并且每次我向下滚动一点或更多,然后 tableView 变慢.
可能是因为 tap/long 按下手势识别器或限制?
应用程序如下所示:
视频卡顿后:
https://www.youtube.com/watch?v=65NkjS-Kz3M
(如果我关闭应用程序并再次打开它,它会再次正常运行,直到我重新加载它几次)
代码:
// 这不是全部代码,我删除了很多不重要的行(比如重新加载函数等)
class ProfileViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITabBarDelegate {
// Classes
let handleData = HandleData()
let handleResponses = HandleResponses()
let worldMessagesFunctions = WorldMessagesFunctions()
let profileFunctions = ProfileFunctions()
// View Objects
@IBOutlet var tableView : UITableView!
// Variables
var userWorldMessages = [WorldMessage]()
var lastContentOffsetY : CGFloat?
var currentSelectedWorldMessageIndexPath : IndexPath?
// Main Code
override func viewDidLoad() {
super.viewDidLoad()
userWorldMessages = ownWorldMessages.shared.worldMessages
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return userWorldMessages.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ProfileWorldMessageCell", for: indexPath) as! ProfileWorldMessageCell
let worldMessage = userWorldMessages[indexPath.row]
cell.worldMessageData = worldMessage
cell.messageLabel.text = worldMessage.message
if let image = UIImage(named: "bubble") {
let h = image.size.height / 2
let w = image.size.width / 2
cell.bubbleImageView.image = image
.resizableImage(withCapInsets:
UIEdgeInsetsMake(h, w, h, w),
resizingMode: .stretch).withRenderingMode(.alwaysTemplate)
cell.bubbleImageView.tintColor = appColors.worldMessageBubble
}
let calendar = NSCalendar.current
let date = Date(timeIntervalSince1970: Double(worldMessage.leftTime))
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US")
var dateFormat = "yyyy MMM dd"
if calendar.isDateInToday(date) {
// Today
dateFormat = "HH:mm"
dateFormatter.string(from: date)
} else if (calendar.date(byAdding: .weekOfYear, value: -1, to: Date())! < date){
// This last 7 days
dateFormat = "EEEE HH:mm"
} else if (calendar.date(byAdding: .month, value: -12, to: Date())! < date){
// This year
dateFormat = "MMM dd"
} else {
dateFormat = "yyyy MMM dd"
}
dateFormatter.dateFormat = dateFormat
let strDate = dateFormatter.string(from: date)
cell.timeLabel.text = strDate
cell.commentsButton.setTitle("\(worldMessage.comments!) comments", for: .normal)
cell.likesButton.setTitle("\(worldMessage.likes!) likes", for: .normal)
// tapped
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(bubbleTappedHandler))
cell.bubbleButton.addGestureRecognizer(tapGestureRecognizer)
cell.bubbleButton.isUserInteractionEnabled = true
// long pressed
let longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(bubbleLongPressHandler))
longPressGestureRecognizer.minimumPressDuration = 0.5
cell.addGestureRecognizer(longPressGestureRecognizer)
cell.isUserInteractionEnabled = true
return cell
}
var cellHeights: [IndexPath : CGFloat] = [:]
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cellHeights[indexPath] = cell.frame.size.height
if indexPath.row == UserWorldMessagesStore.shared.worldMessages.count - 1 && userWorldMessagesCanLoadMore == true {
loadOlderOwnWorldMessages()
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
if cellHeights[indexPath] != nil {
return CGFloat(Float(cellHeights[indexPath] ?? 0.0))
}
else {
return UITableViewAutomaticDimension
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if (lastContentOffsetY != nil){
tableView.setContentOffset(CGPoint(x: 0, y: lastContentOffsetY!), animated: false)
}
}
func loadOlderOwnWorldMessages(){
profileFunctions.loadOlderOwnWorldMessages(startIndex: (userWorldMessages.count)) { response, newUserWorldMessages in
if let response = response {
if response.type == 1 {
DispatchQueue.main.async(execute: {() -> Void in
if newUserWorldMessages != nil {
var insertRows : [IndexPath] = []
var fromIndex = UserWorldMessagesStore.shared.worldMessages.count - 1
for worldMessage in newUserWorldMessages! {
UserWorldMessagesStore.shared.worldMessages.append(worldMessage)
insertRows.append(IndexPath(row: fromIndex, section: 1))
fromIndex += 1
}
self.userWorldMessages = UserWorldMessagesStore.shared.worldMessages
self.tableView.beginUpdates()
self.tableView.insertRows(at: insertRows, with: .automatic)
self.tableView.endUpdates()
}
})
} else {
DispatchQueue.main.async(execute: {() -> Void in
self.handleResponses.displayError(title: response.title, message: response.message)
})
}
}
}
}
@objc func bubbleTappedHandler(sender: UITapGestureRecognizer, should: Bool) {
let touchPoint = sender.location(in: self.tableView)
if let indexPath = tableView.indexPathForRow(at: touchPoint) {
if indexPath == currentSelectedWorldMessageIndexPath {
// it was already selected, so deselect it
deselectCurrentSelectedWorldMessage()
} else {
// select new one, deselect old one if was selected
if (currentSelectedWorldMessageIndexPath != nil){
deselectCurrentSelectedWorldMessage()
}
selectWorldMessage(indexPath: indexPath)
}
}
}
func selectWorldMessage(indexPath: IndexPath) {
tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none)
currentSelectedWorldMessageIndexPath = indexPath
if let cell = tableView.cellForRow(at: indexPath) as? ProfileWorldMessageCell {
// Change some constraints
cell.messageLabelTopConstraint.constant = 14
cell.messageLabelBottomConstraint.constant = 14
UIView.animate(withDuration: 0.15, animations: {
self.view.layoutIfNeeded()
self.tableView.beginUpdates()
self.tableView.endUpdates()
}, completion: nil)
}
}
@objc func deselectCurrentSelectedWorldMessage(){
UIMenuController.shared.setMenuVisible(false, animated: true)
if (currentSelectedWorldMessageIndexPath == nil){
return
}
let indexPath = currentSelectedWorldMessageIndexPath!
if let cell = tableView.cellForRow(at: indexPath) as? ProfileWorldMessageCell {
// Change back some constraints
cell.messageLabelTopConstraint.constant = 10
cell.messageLabelBottomConstraint.constant = 10
UIView.animate(withDuration: 0.15, animations: {
self.view.layoutIfNeeded()
self.tableView.beginUpdates()
self.tableView.endUpdates()
}, completion: nil)
}
currentSelectedWorldMessageIndexPath = nil
}
@objc func bubbleLongPressHandler(sender: UILongPressGestureRecognizer, should: Bool) {
// Show options like copy, delete etc.
}
}
您的 cellForRow
函数有几处 非常 错误:
- 细胞被重复使用,而您忽略了这一事实。每次调用
cellForRow
时,您都在创建手势识别器的新实例,并且在重复使用单元格时,您正在添加另一个。这意味着如果你的单元格被重复使用了 50 次,它将添加 50 个手势识别器。您应该只创建一次手势识别器 - 你每次创建一个
DateFormatter
并设置它的dateFormat
属性,这实际上是一个非常昂贵的过程。相反,您应该为每个日期格式都有一个格式化程序的静态实例