如何在屏幕上显示消息几秒钟?

Bur*_*gan 9 ios swift

我想在用户按下按钮后在屏幕上显示消息.然后我希望消息在大约一秒后消失.优选地,它会消失而不是硬消失.

在显示消息期间,我宁愿不锁定UI.事实上,如果再次按下按钮,我希望计时器重新启动.我不确定是使用NSTimer,dispatch_after,还是有其他选项.

我目前计划使用NSTimer和UI标签来实现这一目标,而我只会忍不住消失.这是最好的方法吗?

编辑:为了澄清,每按一次按钮,消息就不一定相同.我不完全确定这是否相关.

fat*_*han 9

Swift 3解决方案:

  // Define a view
  var popup:UIView!
  func showAlert() {
    // customise your view
    popup = UIView(frame: CGRect(x: 100, y: 200, width: 200, height: 200))
    popup.backgroundColor = UIColor.redColor

    // show on screen
    self.view.addSubview(popup)

    // set the timer
    Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(self.dismissAlert), userInfo: nil, repeats: false)
  }

  func dismissAlert(){
    if popup != nil { // Dismiss the view from here
      popup.removeFromSuperview()
    }
  }
Run Code Online (Sandbox Code Playgroud)

Swift 2解决方案:

  // Define a view
  var popup:UIView!
  func showAlert() {
    // customise your view
    popup = UIView(frame: CGRect(x: 100, y: 200, width: 200, height: 200))
    popup.backgroundColor = UIColor.redColor()

    // show on screen
    self.view.addSubview(popup)

    // set the timer
    NSTimer.scheduledTimerWithTimeInterval(3.0, target: self, selector: Selector("dismissAlert"), userInfo: nil, repeats: false)
  }

  func dismissAlert(){
    // Dismiss the view from here
    popup.removeFromSuperview()
  }

  // Don't forget to call showAlert() function in somewhere
Run Code Online (Sandbox Code Playgroud)


Ale*_*met 8

此代码在 iOS 10 中变得更短。感谢 @fatihyildizhan

func showAlert() {
    let alert = UIAlertController(title: "Alert", message: "Wait Please!", preferredStyle: .alert)
    self.present(alert, animated: true, completion: nil)
    Timer.scheduledTimer(withTimeInterval: 3.0, repeats: false, block: { _ in alert.dismiss(animated: true, completion: nil)} )
}
Run Code Online (Sandbox Code Playgroud)


Bur*_*gan 6

在研究@ mn1的注释中提出的建议之后,我能够完成我想要的。我使用animateWithDuration使标签消失。这是一些示例代码:

myLabel.hidden = false
UIView.animateWithDuration(0.5, animations: { () -> Void in
    self.myLabel.alpha = 0
})
Run Code Online (Sandbox Code Playgroud)


fat*_*han 5

这将在屏幕上显示警报视图,并在1秒后自动关闭.您可以设置时间.

 var alert:UIAlertController!
    func showAlert() {
        self.alert = UIAlertController(title: "Alert", message: "Wait Please!", preferredStyle: UIAlertControllerStyle.Alert)
        self.presentViewController(self.alert, animated: true, completion: nil)
        NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("dismissAlert"), userInfo: nil, repeats: false)
    }

    func dismissAlert(){
        // Dismiss the alert from here
        self.alert.dismissViewControllerAnimated(true, completion: nil)
    }
Run Code Online (Sandbox Code Playgroud)

  • 警报实际上会覆盖按钮并阻止与整个应用程序的交互。我正在寻找一种只向用户显示一些文本而不是突兀的警报的方法。 (2认同)