我想在用户按下按钮后在屏幕上显示一条消息。然后我希望消息在大约一秒钟后消失。最好它会逐渐消失而不是硬消失。
我宁愿在消息显示期间不锁定 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/