如何在swift中逐步更改UILabel文本

时间:2018-05-16 14:06:42

标签: swift

我尝试在我的应用程序中执行加载屏幕,并希望它在UILabel中显示加载状态文本,因此我选择viewDidAppear覆盖功能来完成此操作但是结果是它只显示我设置的已完成文本。这是viewDidAppear中的代码:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(false)
    loadingicon.alpha = 0
    statuslabel.alpha = 0
    loadingicon.alpha = 0
    statuslabel.alpha = 0

    // change 2 to desired number of seconds
    UIView.animate(withDuration: 0.7, animations: {
        //self.imganimation.frame.origin.y -= 150
        self.loadingicon.alpha = 1
        self.statuslabel.alpha = 1
        // self.loadingicon.frame.origin.y -= 50
        // self.statuslabel.frame.origin.y -= 50

    }, completion: nil)

    self.statuslabel.text = "Loading the data"

    sleep(5)

    if CheckInternet.Connection(){
            self.statuslabel.text = "Connection Success"
    } else {
    }
}

正如你所看到的,我试着让系统睡5秒钟,让它一步一步显示我的文字,但是"加载数据"文字消失了,它只显示"连接成功"完成该过程后的文本如何处理此问题

2 个答案:

答案 0 :(得分:0)

使用GCD从当前时间添加延迟。

DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
// Add the code you want to execute after the delay
}

答案 1 :(得分:0)

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(false)
    loadingicon.alpha = 0
    statuslabel.alpha = 0
    loadingicon.alpha = 0
    statuslabel.alpha = 0

    // change 2 to desired number of seconds
    UIView.animate(withDuration: 0.7, animations: {
        //self.imganimation.frame.origin.y -= 150
        self.loadingicon.alpha = 1
        self.statuslabel.alpha = 1
        // self.loadingicon.frame.origin.y -= 50
        // self.statuslabel.frame.origin.y -= 50

    }, completion: nil)

    self.statuslabel.text = "Loading the data"

    DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
      if CheckInternet.Connection(){
              self.statuslabel.text = "Connection Success"
      } else {
      }
  }
}