如何在swift 3中使用diff-diff msg创建Toast通知?

时间:2017-06-24 06:35:27

标签: ios swift

enter image description here

在项目集toast通知中,但是它显示相同的文本,如何在diff文本的相同代码中更改toast通知的文本?

2 个答案:

答案 0 :(得分:3)

您可以使用此简单函数来显示Toast消息,只需传递消息字符串

即可
func displayToastMessage(_ message : String) {

        let toastView = UILabel()
        toastView.backgroundColor = UIColor.black.withAlphaComponent(0.7)
        toastView.textColor = UIColor.white
        toastView.textAlignment = .center
        toastView.font = UIFont.preferredFont(forTextStyle: .caption1)
        toastView.layer.cornerRadius = 25
        toastView.layer.masksToBounds = true
        toastView.text = message
        toastView.numberOfLines = 0
        toastView.alpha = 0
        toastView.translatesAutoresizingMaskIntoConstraints = false

        let window = UIApplication.shared.delegate?.window!
        window?.addSubview(toastView)

        let horizontalCenterContraint: NSLayoutConstraint = NSLayoutConstraint(item: toastView, attribute: .centerX, relatedBy: .equal, toItem: window, attribute: .centerX, multiplier: 1, constant: 0)

        let widthContraint: NSLayoutConstraint = NSLayoutConstraint(item: toastView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: 275)

        let verticalContraint: [NSLayoutConstraint] = NSLayoutConstraint.constraints(withVisualFormat: "V:|-(>=200)-[loginView(==50)]-68-|", options: [.alignAllCenterX, .alignAllCenterY], metrics: nil, views: ["loginView": toastView])

        NSLayoutConstraint.activate([horizontalCenterContraint, widthContraint])
        NSLayoutConstraint.activate(verticalContraint)

        UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseIn, animations: {
            toastView.alpha = 1
        }, completion: nil)

        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double((Int64)(2 * NSEC_PER_SEC)) / Double(NSEC_PER_SEC), execute: {
            UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseIn, animations: {
                toastView.alpha = 0
            }, completion: { finished in
                toastView.removeFromSuperview()
            })
        })
    }

如果您希望能够灵活地在屏幕顶部或底部显示消息,请使用SwiftMessages

答案 1 :(得分:2)

如果只需要简单的Toast消息,而无需自定义字体,对齐方式,文本颜色等,那么下面的方法就可以了

let messageVC = UIAlertController(title: "Message Title", message: "Account Created successfully" , preferredStyle: .actionSheet)
present(messageVC, animated: true) {
                Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false, block: { (_) in
                    messageVC.dismiss(animated: true, completion: nil)})}

.actionSheet从屏幕底部显示警报,计时器负责显示持续时间。将其更改为.alert,以将其显示在屏幕中间。您可以将其添加为UIViewController的扩展,然后从任何地方调用它。或者,如果只需要从一个UIViewController调用它,则只需将其编写为一个函数即可。