简体   繁体   English

在Swift 3中实时重新加载tableview

[英]Reload tableview realtime in Swift 3

How to reload tableview in realtime using timer ? 如何使用timer实时重新加载tableview If viewed, logs are always realtime but in tableview they're not. 如果查看,日志始终是实时的,但在表视图中则不是实时的。 Is there anything less than my coding? 有什么比我的编码少的吗?

@IBOutlet var tableViewChat: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()

    tableViewChat = UITableView(frame: CGRect(x: 0, y: 0, width: 0, height: 0), style: UITableViewStyle.plain)

    startTimer()
}

func startTimer() {
    timer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(GetOrders), userInfo: nil, repeats: true)
    timer.fire()
}

func stopTimer() {
    timer.invalidate()
    timer = nil
}

func GetOrders() {
    getUserOnline()
    getChatMessage()
    DispatchQueue.main.async {
        self.tableViewChat.reloadData()
    }
}

Try changing height of tableview. 尝试更改表格视图的高度。 Now its 0, so I think its not displaying tableview. 现在它是0,所以我认为它不显示tableview。 As your logs are showing properly, as per my knowledge there should be issue with table view height. 由于您的日志显示正确,据我所知,表视图高度应该存在问题。

Your tableViewChat is initialised I storyboard so you don't need this line: 您的tableViewChat已在情节提要中初始化,因此您不需要以下行:

tableViewChat = UITableView(frame: CGRect(x: 0, y: 0, width: 0, height: 0), style: UITableViewStyle.plain)

if you want to change the style do it in storyboard. 如果要更改样式,请在情节提要中进行更改。

Also it looks like you are getting the data asynchronous: 而且看起来您正在异步获取数据:

getUserOnline()
getChatMessage()

Which means that it may take some time to have the data back but you reload the table view straight away: 这意味着可能需要一些时间才能恢复数据,但您需要立即重新加载表格视图:

DispatchQueue.main.async {
    self.tableViewChat.reloadData()
}

At that stage you may not have the data at all (so that's why your table view is empty). 在那个阶段,您可能根本没有数据(因此,表视图为空)。 You need a completion handler or delegate which fires once the data is downloaded and then reload the table view. 您需要一个完成处理程序或委托,该委托处理程序或委托将在数据下载后触发,然后重新加载表视图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM