Swift刷新tableview单元格数据

时间:2016-07-05 09:37:53

标签: ios swift uitableview

我正在使用tableview显示来自json的一些数据。我正在使用一个对象数组来填充这些数据。现在我想在像雅虎板球移动应用程序一定时间(例如10秒)之后刷新这些数据。任何人都可以建议我怎么做?

3 个答案:

答案 0 :(得分:2)

使用计时器是您在ViewDidload

中执行此操作的一种方法
   self.myTimer = NSTimer(timeInterval: 10.0, target: self, selector: "refresh", userInfo: nil, repeats: true)
        NSRunLoop.mainRunLoop().addTimer(self.myTimer, forMode: NSDefaultRunLoopMode)

    func refresh() {
        tableview.reloadData(); //refresh the table
    }

答案 1 :(得分:0)

安排一个每10秒运行一次的计时器

timer = NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: #selectior(refresh), userInfo: nil, repeats: false)
}

func refresh() {
    // fetch Data from Server
}

获取数据后,再次填充数组并使用tableView方法reloadData重新加载tableView

tableview.reloadData()

要更新某些数据行,您可以使用下面的代码。这里我演示了一行更新,你可以通过在你想要的数组中传递indexPath多个来进行多行更新。

//suppose you want to update row 0 for section 0, create indexPath as
let indexPath1 = NSIndexPath(forRow: 0, inSection: 0)
tableview.reloadRowsAtIndexPaths([indexPath1], withRowAnimation: .Automatic)

如果您想更新特定部分,请执行此操作

//suppose you want to update your section 0
let indexSet = NSIndexSet(index: 0)
profileTableView.reloadSections(indexSet, withRowAnimation: .Automatic)

答案 2 :(得分:0)

最简单的方法是使用NSTimer。

class ViewController: UIViewController {

    var timer : NSTimer!
    override func viewDidLoad() {
        super.viewDidLoad()
        timer = NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: #selectior(fetch), userInfo: nil, repeats: false)
    }

    func fetch() {
        // do your stuff here
    }
}
相关问题