What is the android.widget.Toast equivalent for iOS applications?

前端 未结 6 2202
灰色年华
灰色年华 2020-12-13 05:44

I have made Android application a few months ago. The Toast class is very useful for me. I do not need to consider the main Thread and place to show it. Anywhere I can show

6条回答
  •  孤街浪徒
    2020-12-13 06:32

    I'm posting swift version of Scarmysun answer:) many thanks

    import Foundation
    import UIKit
    
    class ToastView: UIView {
        static let toastHeight:CGFloat = 50.0
        static let toastGap:CGFloat = 10;
        lazy var textLabel: UILabel = UILabel(frame: CGRectMake(5.0, 5.0, self.frame.size.width - 10.0, self.frame.size.height - 10.0))
    
    
        static func showInParent(parentView: UIView!, withText text: String, forDuration duration: double_t) {
    
            //Count toast views are already showing on parent. Made to show several toasts one above another
            var toastsAlreadyInParent = 0;
    
            for view in parentView.subviews {
                if (view.isKindOfClass(ToastView)) {
                    toastsAlreadyInParent++
                }
            }
    
            var parentFrame = parentView.frame;
    
            var yOrigin = parentFrame.size.height - getDouble(toastsAlreadyInParent)
    
            var selfFrame = CGRectMake(parentFrame.origin.x + 20.0, yOrigin, parentFrame.size.width - 40.0, toastHeight);
            var toast = ToastView(frame: selfFrame)
    
            toast.textLabel.backgroundColor = UIColor.clearColor()
            toast.textLabel.textAlignment = NSTextAlignment.Center
            toast.textLabel.textColor = UIColor.whiteColor()
            toast.textLabel.numberOfLines = 2
            toast.textLabel.font = UIFont.systemFontOfSize(13.0)
            toast.addSubview(toast.textLabel)
    
            toast.backgroundColor = UIColor.darkGrayColor()
            toast.alpha = 0.0;
            toast.layer.cornerRadius = 4.0;
            toast.textLabel.text = text;
    
            parentView.addSubview(toast)
            UIView.animateWithDuration(0.4, animations: {
                toast.alpha = 0.9
                toast.textLabel.alpha = 0.9
            })
    
    
            toast.performSelector(Selector("hideSelf"), withObject: nil, afterDelay: duration)
    
        }
    
        static private func getDouble(toastsAlreadyInParent : Int) -> CGFloat {
            return (70.0 + toastHeight * CGFloat(toastsAlreadyInParent) + toastGap * CGFloat(toastsAlreadyInParent));
        }
    
         func hideSelf() {
            UIView.animateWithDuration(0.4, animations: {
                self.alpha = 0.0
                self.textLabel.alpha = 0.0
            }, completion: { t in self.removeFromSuperview() })
        }
    
    }
    

提交回复
热议问题