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

标签 ios swift

我想在用户按下按钮后在屏幕上显示一条消息。然后我希望消息在大约一秒钟后消失。最好它会逐渐消失而不是硬消失。

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

我目前计划使用一个 NSTimer 和一个 UI 标签来实现这一点,我将忍受硬消失。这是最好的方法吗?

编辑:澄清一下,每次按下按钮时,消息不一定都相同。不过,我不完全确定这是否相关。

最佳答案

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()
    }
  }

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

关于ios - 如何在屏幕上显示几秒钟的消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33861565/

相关文章:

ios - 如何以编程方式在 Outlook 中添加附件 swift 3

objective-c - 强制将特定本地化用于目标

Swift - UIStoryboardSegue 以编程方式弹出 ViewController

ios - 我想在点击它时更改 UIButton 图像

ios - 根据 Swift 中的 UILabel 文本调整 UIView 高度

ios - 如何从 INDEXPATH.ROW 的属性设置标题部分的标题

ios - 即使应用程序处于非事件状态也显示 Alertview

ios - 'AcceptView' 没有可见的@interface 声明选择器 'presentViewController:animated:completion:'

ios - NSException 的终止异常类型

ios - 使用 rxSwift 进行长轮询