Jae*_*Kim 4 xcode uitableview ios swift
我想知道如何自动刷新tableview而不必下拉刷新.所以我尝试设置NSTimer并调用一个具有的函数reloadData().但那没用.换句话说,我做了:
@IBOutlet weak var allPrayerRequestsTableView: UITableView!
var timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: "update", userInfo: nil, repeats: true)
func update() {
allPrayerRequestsTableView.reloadData()
}
Run Code Online (Sandbox Code Playgroud)
但这没效果.有人知道如何每隔几秒自动刷新一次tableview吗?
尝试以这种方式在主线程中重新加载tableview:
dispatch_async(dispatch_get_main_queue()) {
self.allPrayerRequestsTableView.reloadData()
}
Run Code Online (Sandbox Code Playgroud)
你的方法将是:
func update() {
dispatch_async(dispatch_get_main_queue()) {
self.allPrayerRequestsTableView.reloadData()
}
}
Run Code Online (Sandbox Code Playgroud)
示例代码:
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var allPrayerRequestsTableView: UITableView!
var tableArray = [Int]()
var count = 0
override func viewDidLoad() {
super.viewDidLoad()
allPrayerRequestsTableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
allPrayerRequestsTableView.delegate = self
allPrayerRequestsTableView.dataSource = self
var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "update", userInfo: nil, repeats: true)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return tableArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell
cell.textLabel?.text = "\(tableArray[indexPath.row])"
return cell
}
func update() {
count++
//update your table data here
tableArray.append(count)
dispatch_async(dispatch_get_main_queue()) {
self.allPrayerRequestsTableView.reloadData()
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是最后的项目.
| 归档时间: |
|
| 查看次数: |
6591 次 |
| 最近记录: |