Displaying a message in iOS which has the same functionality as Toast in Android

前端 未结 19 1741
逝去的感伤
逝去的感伤 2020-12-12 12:35

I need to know if there is any method in iOS which behaves like Toast messages in Android. That is, I need to display a message which is dismissed automatically after few se

19条回答
  •  醉酒成梦
    2020-12-12 13:21

    Swift 4

    How about this small trick?

    func showToast(controller: UIViewController, message : String, seconds: Double) {
        let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
        alert.view.backgroundColor = UIColor.black
        alert.view.alpha = 0.6
        alert.view.layer.cornerRadius = 15
    
        controller.present(alert, animated: true)
    
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + seconds) {
            alert.dismiss(animated: true)
        }
    }
    

    Example of calling:

    showToast(controller: self, message : "This is a test", seconds: 2.0)
    

    Output:

提交回复
热议问题