ios – 自动刷新tableview,无需刷新

前端之家收集整理的这篇文章主要介绍了ios – 自动刷新tableview,无需刷新前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想知道如何自动刷新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吗?

解决方法

尝试以这种方式在主线程中重新加载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是最终项目.

猜你在找的Xcode相关文章