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

前端 未结 19 1735
逝去的感伤
逝去的感伤 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:29

    This is how I have done in Swift 3.0. I created UIView extension and calling the self.view.showToast(message: "Message Here", duration: 3.0) and self.view.hideToast()

    extension UIView{
    var showToastTag :Int {return 999}
    
    //Generic Show toast
    func showToast(message : String, duration:TimeInterval) {
    
        let toastLabel = UILabel(frame: CGRect(x:0, y:0, width: (self.frame.size.width)-60, height:64))
    
        toastLabel.backgroundColor = UIColor.gray
        toastLabel.textColor = UIColor.black
        toastLabel.numberOfLines = 0
        toastLabel.layer.borderColor = UIColor.lightGray.cgColor
        toastLabel.layer.borderWidth = 1.0
        toastLabel.textAlignment = .center;
        toastLabel.font = UIFont(name: "HelveticaNeue", size: 17.0)
        toastLabel.text = message
        toastLabel.center = self.center
        toastLabel.isEnabled = true
        toastLabel.alpha = 0.99
        toastLabel.tag = showToastTag
        toastLabel.layer.cornerRadius = 10;
        toastLabel.clipsToBounds  =  true
        self.addSubview(toastLabel)
    
        UIView.animate(withDuration: duration, delay: 0.1, options: .curveEaseOut, animations: {
            toastLabel.alpha = 0.95
        }, completion: {(isCompleted) in
            toastLabel.removeFromSuperview()
        })
    }
    
    //Generic Hide toast
    func hideToast(){
        if let view = self.viewWithTag(self.showToastTag){
            view.removeFromSuperview()
        }
      }
    }
    

提交回复
热议问题