在swift 4中添加带定时器的导航栏刷新按钮

时间:2018-01-03 10:49:11

标签: ios swift uitableview swift4

我试图添加一个导航栏刷新按钮来更新来自JSON的表格视图内容,此外我希望我的表格视图每5分钟自动更新一次,如果用户没有按下刷新按钮并将按钮更改为活动指示器,以便在表视图更新数据时让正在更新的用户

refresh button image

我的刷新按钮IBAction代码:

@IBAction func refreshButton(_ sender: Any) {

    self.getCoinData()
    self.coinTableView.reloadData()
}

3 个答案:

答案 0 :(得分:4)

Swift 4 +

创建计时器&完成webservice后显示重新加载图标

class ViewController: UIViewController {

    var timer: Timer!
    var refreshBarButtonActivityIndicator: UIBarButtonItem!
    var refreshBarButton: UIBarButtonItem!
    override func viewDidLoad() {
        super.viewDidLoad()
        barItemSetUp()
    }
    func barItemSetUp() {
        ///SettingReloadButton
        let image = UIImage(named: "refresh-25")?.withRenderingMode(.alwaysOriginal)
        refreshBarButton = UIBarButtonItem(image: image, style: .plain, target: self, action: nil)
        ///Setting activity Indicator
        let activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView.init(activityIndicatorStyle: .gray)
        refreshBarButtonActivityIndicator = UIBarButtonItem(customView: activityIndicator)
        activityIndicator.startAnimating()
        toogleIndicator()
    }
   deinit {    
     timer?.invalidate()
   }
    func toogleIndicator() {
        // 5 minutes = 300 seconds //write here 300
        timer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(refreshNow), userInfo: nil, repeats: true)
    }

    @objc func refreshNow() {
        //here i am creating delay for sample purpose
        //here write your webservice code on completion of webservice change bar button item
        self.navigationItem.rightBarButtonItem = refreshBarButtonActivityIndicator
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
            self.navigationItem.rightBarButtonItem = self.refreshBarButton
        }
    }
}

<强>输出: -

enter image description here

答案 1 :(得分:0)

首先添加每5分钟刷新一次的计时器。在计时器,您添加Web服务。

var timer = Timer()
func runTimer(){
    timer = Timer.scheduledTimer(timeInterval: 5, target: self,   selector: (#selector(self.updateTimer)), userInfo: nil, repeats: true)
}
func updateTimer() {
    self.getCoinData()
    self.coinTableView.reloadData()
}
override func viewWillAppear(_ animated: Bool){
    runTimer()      
}

答案 2 :(得分:0)

要在每5分钟后重新加载UITableView,您需要安排一个Timer,每隔5分钟执行一段代码,即

var timer: Timer?

override func viewDidLoad()
{
    super.viewDidLoad()
    self.timer = Timer.scheduledTimer(withTimeInterval: 300, repeats: true, block: {[weak self] (tt) in
        self?.getCoinData()
        self?.coinTableView.reloadData()
    })
    timer?.fire()
}

deinit
{
    timer?.invalidate()
}

您可以根据需要更改时间间隔。您需要以秒为单位给出时间间隔。