我想知道如何自动刷新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() }
解决方法
尝试以这种方式在主线程中重新加载tableview:
dispatch_async(dispatch_get_main_queue()) { self.allPrayerRequestsTableView.reloadData() }
你的方法将是:
func update() { dispatch_async(dispatch_get_main_queue()) { self.allPrayerRequestsTableView.reloadData() } }
示例代码:
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,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() } } }
HERE是最终项目.