如何在Swift中敬酒消息?


Answers:


164
extension UIViewController {

func showToast(message : String, font: UIFont) {

    let toastLabel = UILabel(frame: CGRect(x: self.view.frame.size.width/2 - 75, y: self.view.frame.size.height-100, width: 150, height: 35))
    toastLabel.backgroundColor = UIColor.black.withAlphaComponent(0.6)
    toastLabel.textColor = UIColor.white
    toastLabel.font = font
    toastLabel.textAlignment = .center;
    toastLabel.text = message
    toastLabel.alpha = 1.0
    toastLabel.layer.cornerRadius = 10;
    toastLabel.clipsToBounds  =  true
    self.view.addSubview(toastLabel)
    UIView.animate(withDuration: 4.0, delay: 0.1, options: .curveEaseOut, animations: {
         toastLabel.alpha = 0.0
    }, completion: {(isCompleted) in
        toastLabel.removeFromSuperview()
    })
} }

像这样使用:

self.showToast(message: "Your Toast Message", font: .systemFont(ofSize: 12.0))

4
完美的答案。您可以添加'toastLabel.font = UIFont(name:“ IranSansMobile”,size:19)'以更改Toast消息的字体。
Milad Faridnia '17

1
动画结束后,应从视图中删除标签。
Sulthan

1
@Sulthan欢迎您编辑或升级答案,否则我将尽快更新答案!
Bean先生

2
如果要显示多行显示的完整消息,则可以使用如下所示:let toastLabel = UILabel(frame:CGRect(x:0,y:self.view.frame.size.height-100,width:(self。 view.frame.width-10),高度:35))toastLabel.numberOfLines = 0,您可以相应地更改高度。
Udaya Sri

2
答案几乎是完美的,因为如果您在全屏模式下显示某些内容,它将无法正常工作,您需要通过UIApplication.shared.keyWindow?.addSubview(toastLabel)更改addsubview
Jean Raymond Daher

51

对于Swift 4

我使用布局约束的Toast版本,其优点是可以按任意大小使用文本(基于Tony Franzis的回复):

只需致电: Toast.show(message: "My message", myViewControllerName)

class Toast {
    static func show(message: String, controller: UIViewController) {
        let toastContainer = UIView(frame: CGRect())
        toastContainer.backgroundColor = UIColor.black.withAlphaComponent(0.6)
        toastContainer.alpha = 0.0
        toastContainer.layer.cornerRadius = 25;
        toastContainer.clipsToBounds  =  true

        let toastLabel = UILabel(frame: CGRect())
        toastLabel.textColor = UIColor.white
        toastLabel.textAlignment = .center;
        toastLabel.font.withSize(12.0)
        toastLabel.text = message
        toastLabel.clipsToBounds  =  true
        toastLabel.numberOfLines = 0

        toastContainer.addSubview(toastLabel)
        controller.view.addSubview(toastContainer)

        toastLabel.translatesAutoresizingMaskIntoConstraints = false
        toastContainer.translatesAutoresizingMaskIntoConstraints = false

        let a1 = NSLayoutConstraint(item: toastLabel, attribute: .leading, relatedBy: .equal, toItem: toastContainer, attribute: .leading, multiplier: 1, constant: 15)
        let a2 = NSLayoutConstraint(item: toastLabel, attribute: .trailing, relatedBy: .equal, toItem: toastContainer, attribute: .trailing, multiplier: 1, constant: -15)
        let a3 = NSLayoutConstraint(item: toastLabel, attribute: .bottom, relatedBy: .equal, toItem: toastContainer, attribute: .bottom, multiplier: 1, constant: -15)
        let a4 = NSLayoutConstraint(item: toastLabel, attribute: .top, relatedBy: .equal, toItem: toastContainer, attribute: .top, multiplier: 1, constant: 15)
        toastContainer.addConstraints([a1, a2, a3, a4])

        let c1 = NSLayoutConstraint(item: toastContainer, attribute: .leading, relatedBy: .equal, toItem: controller.view, attribute: .leading, multiplier: 1, constant: 65)
        let c2 = NSLayoutConstraint(item: toastContainer, attribute: .trailing, relatedBy: .equal, toItem: controller.view, attribute: .trailing, multiplier: 1, constant: -65)
        let c3 = NSLayoutConstraint(item: toastContainer, attribute: .bottom, relatedBy: .equal, toItem: controller.view, attribute: .bottom, multiplier: 1, constant: -75)
        controller.view.addConstraints([c1, c2, c3])

        UIView.animate(withDuration: 0.5, delay: 0.0, options: .curveEaseIn, animations: {
            toastContainer.alpha = 1.0
        }, completion: { _ in
            UIView.animate(withDuration: 0.5, delay: 1.5, options: .curveEaseOut, animations: {
                toastContainer.alpha = 0.0
            }, completion: {_ in
                toastContainer.removeFromSuperview()
            })
        })
    }
}

2
有很多可供选择的地方。我选了这个。
Dale

@Samo很好,谢谢。使用iPhone X时,只是toastContainer被部分隐藏在UITabBar的后面。在c3中,我将-75更改为-100以修复它。
Mario Huizinga

它很棒,可以让您在没有第三方的情况下进行操作。我在应用程序中的任何地方重复使用它。感谢您的回答。
Onur Tuna

1
精彩!但是我更改了toastContainer的约束,使其具有动态宽度,并将其作为UIViewController的扩展。这里是:让c1 = NSLayoutConstraint(项目:toastContainer,属性:.width,relatedBy:.lessThanOrEqual,toItem:视图,属性:.width,乘数:1,常数:-90)让c2 = NSLayoutConstraint(项目:toastContainer,属性:.centerX,relatedBy:.equal,toItem:view,attribute:.centerX,multiplier:1,constant:1)
sVd19年

27

斯威夫特4

func showToast(message : String) {

    let toastLabel = UILabel(frame: CGRect(x: self.view.frame.size.width/2 - 75, y: self.view.frame.size.height-100, width: 150, height: 35))
    toastLabel.backgroundColor = UIColor.black.withAlphaComponent(0.6)
    toastLabel.textColor = UIColor.white
    toastLabel.textAlignment = .center;
    toastLabel.font = UIFont(name: "Montserrat-Light", size: 12.0)
    toastLabel.text = message
    toastLabel.alpha = 1.0
    toastLabel.layer.cornerRadius = 10;
    toastLabel.clipsToBounds  =  true
    self.view.addSubview(toastLabel)
    UIView.animate(withDuration: 4.0, delay: 0.1, options: .curveEaseOut, animations: {
        toastLabel.alpha = 0.0
    }, completion: {(isCompleted) in
        toastLabel.removeFromSuperview()
    })
}

像这样调用函数

self.showToast(message: "Data Save.")

1
我将从a开始,toastLabel.alpha = 0.0然后做以下动画: UIView.animate(withDuration: 0.5, delay: 0.0, options: .curveEaseIn, animations: { toastLabel.alpha = 1.0 }, completion: { _ in UIView.animate(withDuration: 0.5, delay: 1.5, options: .curveEaseOut, animations: { toastLabel.alpha = 0.0 }, completion: {_ in toastLabel.removeFromSuperview() }) })
Samo

1
因显示如何调用而被赞誉,大多数答案只是显示该函数而忘记了如何调用
DragonFire '19

13

只需添加以下方法。这将通过动画以不同的颜色显示消息(消息从左到右出现并消失)。

斯威夫特3.0-

class Toast
{
    class private func showAlert(backgroundColor:UIColor, textColor:UIColor, message:String)
    {

        let appDelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
        let label = UILabel(frame: CGRect.zero)
        label.textAlignment = NSTextAlignment.center
        label.text = message
        label.font = UIFont(name: "", size: 15)
        label.adjustsFontSizeToFitWidth = true

        label.backgroundColor =  backgroundColor //UIColor.whiteColor()
        label.textColor = textColor //TEXT COLOR

        label.sizeToFit()
        label.numberOfLines = 4
        label.layer.shadowColor = UIColor.gray.cgColor
        label.layer.shadowOffset = CGSize(width: 4, height: 3)
        label.layer.shadowOpacity = 0.3
        label.frame = CGRect(x: appDelegate.window!.frame.size.width, y: 64, width: appDelegate.window!.frame.size.width, height: 44)

        label.alpha = 1

        appDelegate.window!.addSubview(label)

        var basketTopFrame: CGRect = label.frame;
        basketTopFrame.origin.x = 0;

        UIView.animate(withDuration
            :2.0, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.1, options: UIViewAnimationOptions.curveEaseOut, animations: { () -> Void in
                label.frame = basketTopFrame
        },  completion: {
            (value: Bool) in
            UIView.animate(withDuration:2.0, delay: 2.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.1, options: UIViewAnimationOptions.curveEaseIn, animations: { () -> Void in
                label.alpha = 0
            },  completion: {
                (value: Bool) in
                label.removeFromSuperview()
            })
        })
    }

    class func showPositiveMessage(message:String)
    {
        showAlert(backgroundColor: UIColor.green, textColor: UIColor.white, message: message)
    }
    class func showNegativeMessage(message:String)
    {
        showAlert(backgroundColor: UIColor.red, textColor: UIColor.white, message: message)
    }
}

11

您真正需要的是https://github.com/Rannie/Toast-Swift/blob/master/SwiftToastDemo/Toast/HRToast%2BUIView.swift

下载HRToast + UIView.swift类并将其拖放到项目中。确保在对话框上选中“如果需要,复制项目”。

  //Usage:
  self.view.makeToast(message: "Simple Toast")
  self.view.makeToast(message: "Simple Toast", duration: 2.0, position:HRToastPositionTop)

  self.view.makeToast(message: "Simple Toast", duration: 2.0, position: HRToastPositionCenter, image: UIImage(named: "ic_120x120")!)

  self.view.makeToast(message: "It is just awesome", duration: 2.0, position: HRToastPositionDefault, title: "Simple Toast")

  self.view.makeToast(message: "It is just awesome", duration: 2.0, position: HRToastPositionCenter, title: "Simple Toast", image: UIImage(named: "ic_120x120")!)

  self.view.makeToastActivity()
  self.view.makeToastActivity(position: HRToastPositionCenter)
  self.view.makeToastActivity(position: HRToastPositionDefault, message: "Loading")
  self.view.makeToastActivityWithMessage(message: "Loading")

我如何更改吐司的颜色..当我尝试吐司时self.view.hr_setToastThemeColor(color: #ThemeColor)出现错误
Dory

11

有一个第三方库,支持使用单行代码进行自定义的Toast通知。这是一个简单的例子:

import Toast_Swift

...

// basic usage
self.view.makeToast("This is a piece of toast")

// toast with a specific duration and position
self.view.makeToast("This is a piece of toast", duration: 3.0, position: .top)

https://github.com/scalessec/Toast-Swift

(已更新为Swift 3/4 +)


8

当我需要像Android这样的Toast消息时,我就一直在使用此扩展。只需将扩展复制到您的项目中,然后在您的UIViewController类中,调用类似

self.toastMessage("Downloading...") 
// Extention is below

extension UIViewController {
  func toastMessage(_ message: String){
    guard let window = UIApplication.shared.keyWindow else {return}
    let messageLbl = UILabel()
    messageLbl.text = message
    messageLbl.textAlignment = .center
    messageLbl.font = UIFont.systemFont(ofSize: 12)
    messageLbl.textColor = .white
    messageLbl.backgroundColor = UIColor(white: 0, alpha: 0.5)

    let textSize:CGSize = messageLbl.intrinsicContentSize
    let labelWidth = min(textSize.width, window.frame.width - 40)

    messageLbl.frame = CGRect(x: 20, y: window.frame.height - 90, width: labelWidth + 30, height: textSize.height + 20)
    messageLbl.center.x = window.center.x
    messageLbl.layer.cornerRadius = messageLbl.frame.height/2
    messageLbl.layer.masksToBounds = true
    window.addSubview(messageLbl)

    DispatchQueue.main.asyncAfter(deadline: .now() + 1) {

    UIView.animate(withDuration: 1, animations: {
        messageLbl.alpha = 0
    }) { (_) in
        messageLbl.removeFromSuperview()
    }
    }
}}

不要只是脱口而出代码!添加一些文字来描述此代码如何最好地回答问题,将提高答案的长期价值,并有助于防止其在审阅过程中被删除。
NightOwl888 '18

1
代码是不言自明的先生,但我仍在编辑。如果操作不正确,请告知。
Gopal krishan

7

我在Swift 5上还有两个解决方案:

最佳解决方案(我认为)

优点:

  1. 旋转屏幕时可以正常工作。
  2. 约束用于定位。
  3. 与SafeArea一起正常工作。

缺点:

  1. 需要扩展UILabel类以添加缩进。如果没有此功能,可以将放置在UILabelUIVIew

码:

class ToastLabel: UILabel {
    var textInsets = UIEdgeInsets.zero {
        didSet { invalidateIntrinsicContentSize() }
    }

    override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
        let insetRect = bounds.inset(by: textInsets)
        let textRect = super.textRect(forBounds: insetRect, limitedToNumberOfLines: numberOfLines)
        let invertedInsets = UIEdgeInsets(top: -textInsets.top, left: -textInsets.left, bottom: -textInsets.bottom, right: -textInsets.right)

        return textRect.inset(by: invertedInsets)
    }

    override func drawText(in rect: CGRect) {
        super.drawText(in: rect.inset(by: textInsets))
    }
}

extension UIViewController {
    static let DELAY_SHORT = 1.5
    static let DELAY_LONG = 3.0

    func showToast(_ text: String, delay: TimeInterval = DELAY_LONG) {
        let label = ToastLabel()
        label.backgroundColor = UIColor(white: 0, alpha: 0.5)
        label.textColor = .white
        label.textAlignment = .center
        label.font = UIFont.systemFont(ofSize: 15)
        label.alpha = 0
        label.text = text
        label.clipsToBounds = true
        label.layer.cornerRadius = 20
        label.numberOfLines = 0
        label.textInsets = UIEdgeInsets(top: 10, left: 15, bottom: 10, right: 15)
        label.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(label)

        let saveArea = view.safeAreaLayoutGuide
        label.centerXAnchor.constraint(equalTo: saveArea.centerXAnchor, constant: 0).isActive = true
        label.leadingAnchor.constraint(greaterThanOrEqualTo: saveArea.leadingAnchor, constant: 15).isActive = true
        label.trailingAnchor.constraint(lessThanOrEqualTo: saveArea.trailingAnchor, constant: -15).isActive = true
        label.bottomAnchor.constraint(equalTo: saveArea.bottomAnchor, constant: -30).isActive = true

        UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseIn, animations: {
            label.alpha = 1
        }, completion: { _ in
            UIView.animate(withDuration: 0.5, delay: delay, options: .curveEaseOut, animations: {
                label.alpha = 0
            }, completion: {_ in
                label.removeFromSuperview()
            })
        })
    }
}

如何使用:

class MyController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        showToast("Message")
    }
}

其他解决方案

优点:

  1. 在此版本中,我不使用绑定 UIViewController

缺点:

  1. 屏幕旋转后,标签不会移动。
  2. 在多行字符串中无法正常使用。

码:

class Helper {
    static let DELAY_SHORT = 1.5
    static let DELAY_LONG = 3.0

    static func showToast(_ text: String, delay: TimeInterval = DELAY_LONG) {
        guard let window = UIApplication.shared.keyWindow else {
            return
        }

        let label = BaseLabel()
        label.backgroundColor = UIColor(white: 0, alpha: 0.5)
        label.textColor = .white
        label.textAlignment = .center
        label.font = UIFont.systemFont(ofSize: 15)
        label.alpha = 0
        label.text = text
        label.numberOfLines = 0

        var vertical: CGFloat = 0
        var size = label.intrinsicContentSize
        var width = min(size.width, window.frame.width - 60)
        if width != size.width {
            vertical = 10
            label.textAlignment = .justified
        }
        label.textInsets = UIEdgeInsets(top: vertical, left: 15, bottom: vertical, right: 15)

        size = label.intrinsicContentSize
        width = min(size.width, window.frame.width - 60)

        label.frame = CGRect(x: 20, y: window.frame.height - 90, width: width, height: size.height + 20)
        label.center.x = window.center.x
        label.layer.cornerRadius = min(label.frame.height/2, 25)
        label.layer.masksToBounds = true
        window.addSubview(label)

        UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseIn, animations: {
            label.alpha = 1
        }, completion: { _ in
            UIView.animate(withDuration: 0.5, delay: delay, options: .curveEaseOut, animations: {
                label.alpha = 0
            }, completion: {_ in
                label.removeFromSuperview()
            })
        })
    }
}

如何使用:

Helper.showToast("Message")

您还可以添加label.heightAnchor.constraint(equalToConstant: 35).active = true以设置视图高度,以便标签在文本上方和下方保留间距。
siralexsir88

5

Swift 5,如果您想使用简单的烤面包,请在下面找到代码。

extension UIViewController{

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

从UIViewController调用

  self.showToast(message: "Updating...", seconds: 1.0)

4

如果只需要简单的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从屏幕底部显示警报,计时器负责显示持续时间。您可以将其添加为UIViewController的扩展,然后从任何地方调用它。


3

如果makeToast:duration:position:在Objective-C中定义并可以调用,则快速代码为

self.view.makeToast("Acount created Successfully", duration: 0.5, position: "bottom")

不过,您可能需要使用桥接标头来访问快速代码中的那些方法。


3

@ mr-bean代码已更新为最新的Swift版本(3.x)

    let toastLabel =
        UILabel(frame:
            CGRect(x: self.view.frame.size.width/2 - 150,
                   y: self.view.frame.size.height-100,
                   width: 300,
                   height: 35))
    toastLabel.backgroundColor = UIColor.black
    toastLabel.textColor = UIColor.white
    toastLabel.textAlignment = NSTextAlignment.center
    self.view.addSubview(toastLabel)
    toastLabel.text = message
    toastLabel.alpha = 1.0
    toastLabel.layer.cornerRadius = 10;
    toastLabel.clipsToBounds  =  true
    UIView.animate(withDuration: 4.0, animations: {
        toastLabel.alpha = 0.0
    })

3

我用以下方式修改了@samo的答案:

  • 正确的变量名称

  • 前导约束和尾随约束更改为中心约束。

现在,消息将根据消息调整其宽度,并将其居中。

extension UIViewController {
        func showToast(message: String) {
            let toastContainer = UIView(frame: CGRect())
            toastContainer.backgroundColor = UIColor.black.withAlphaComponent(0.6)
            toastContainer.alpha = 0.0
            toastContainer.layer.cornerRadius = 20;
            toastContainer.clipsToBounds  =  true

            let toastLabel = UILabel(frame: CGRect())
            toastLabel.textColor = UIColor.white
            toastLabel.textAlignment = .center;
            toastLabel.font.withSize(12.0)
            toastLabel.text = message
            toastLabel.clipsToBounds  =  true
            toastLabel.numberOfLines = 0

            toastContainer.addSubview(toastLabel)
            self.view.addSubview(toastContainer)

            toastLabel.translatesAutoresizingMaskIntoConstraints = false
            toastContainer.translatesAutoresizingMaskIntoConstraints = false

            let centerX = NSLayoutConstraint(item: toastLabel, attribute: .centerX, relatedBy: .equal, toItem: toastContainer, attribute: .centerXWithinMargins, multiplier: 1, constant: 0)
            let lableBottom = NSLayoutConstraint(item: toastLabel, attribute: .bottom, relatedBy: .equal, toItem: toastContainer, attribute: .bottom, multiplier: 1, constant: -15)
            let lableTop = NSLayoutConstraint(item: toastLabel, attribute: .top, relatedBy: .equal, toItem: toastContainer, attribute: .top, multiplier: 1, constant: 15)
            toastContainer.addConstraints([centerX, lableBottom, lableTop])

            let containerCenterX = NSLayoutConstraint(item: toastContainer, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1, constant: 0)
            let containerTrailing = NSLayoutConstraint(item: toastContainer, attribute: .width, relatedBy: .equal, toItem: toastLabel, attribute: .width, multiplier: 1.1, constant: 0)
            let containerBottom = NSLayoutConstraint(item: toastContainer, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1, constant: -75)
            self.view.addConstraints([containerCenterX,containerTrailing, containerBottom])

            UIView.animate(withDuration: 0.5, delay: 0.0, options: .curveEaseIn, animations: {
                toastContainer.alpha = 1.0
            }, completion: { _ in
                UIView.animate(withDuration: 0.5, delay: 1.5, options: .curveEaseOut, animations: {
                    toastContainer.alpha = 0.0
                }, completion: {_ in
                    toastContainer.removeFromSuperview()
                })
            })
        }
    }

调整大小效果很好,但是您不能设置字体大小
user2161301

toastLabel.font = toastLabel.font.withSize(40)
user2161301

1

而不是UILabel使用UITextView获得更好的结果。

func showToast(message: String) {
        let toastLabel = UITextView(frame: CGRect(x: self.view.frame.size.width/16, y: self.view.frame.size.height-150, width: self.view.frame.size.width * 7/8, height: 35))
        toastLabel.backgroundColor = UIColor.black.withAlphaComponent(0.6)
        toastLabel.textColor = UIColor.white
        toastLabel.textAlignment = .center;
        toastLabel.text = "   \(message)   "
        toastLabel.alpha = 1.0
        toastLabel.layer.cornerRadius = 10;
        toastLabel.clipsToBounds  =  true
        toastLabel.font = UIFont(name: (toastLabel.font?.fontName)!, size: 16)
        toastLabel.layoutEdgeInsets.left = 8
        toastLabel.layoutEdgeInsets.right = 8
        toastLabel.center.x = self.view.frame.size.width/2
        self.view.addSubview(toastLabel)
        UIView.animate(withDuration: 5.0, delay: 0.1, options: .curveEaseOut, animations: {
            toastLabel.alpha = 0.0
        }, completion: {(isCompleted) in
            toastLabel.removeFromSuperview()
        })
}

消息中添加了空格,以在两端提供良好的间距,从而看起来不错。豆先生的答案的修改后的版本


1

我知道有公认的答案,但它们似乎都存在很大缺陷-如果您在短时间内展示多个吐司,它们将彼此重叠。这是我的实现,其中考虑了此问题:

class Toast: UILabel {

private let BOTTOM_MARGIN: CGFloat = 16
private let SIDE_MARGIN: CGFloat = 16
private let HEIGHT: CGFloat = 35
private let SHOW_TIME_SECONDS = TimeInterval(3)
private let BACKGROUND_COLOR = UIColor.darkGray.withAlphaComponent(0.7).cgColor
private let TEXT_COLOR = UIColor.white
private let ANIMATION_DURATION_SEC = 0.33

private static var queue: [ToastHolder] = []
private static var showing: Toast?

init(_ text: String) {
    super.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0))

    self.text = text
    self.textColor = TEXT_COLOR
    textAlignment = .center
    self.layer.backgroundColor = BACKGROUND_COLOR
    self.layer.cornerRadius = 5
}

public func show(_ parent: UIViewController) {
    frame = CGRect(x: SIDE_MARGIN, y: UIScreen.main.bounds.height - BOTTOM_MARGIN - HEIGHT, width: UIScreen.main.bounds.width - 2 * SIDE_MARGIN, height: HEIGHT)

    if Toast.showing == nil {
        Log.d("showing \(String(describing: text))")
        Toast.showing = self
        alpha = 0
        parent.view.addSubview(self)
        UIView.animate(withDuration: ANIMATION_DURATION_SEC, animations: {
            self.alpha = 1
        }, completion: { (completed) in
            Timer.scheduledTimer(timeInterval: self.SHOW_TIME_SECONDS, target: self, selector: #selector(self.onTimeout), userInfo: nil, repeats: false)
        })
    } else {
        Toast.queue.append(ToastHolder(self, parent))
    }
}

@objc func onTimeout() {        
    UIView.animate(withDuration: ANIMATION_DURATION_SEC, animations: {
        self.alpha = 0
    }, completion: { (completed) in
        Toast.showing = nil
        self.removeFromSuperview()

        if !Toast.queue.isEmpty {
            let holder = Toast.queue.removeFirst()
            holder.toast.show(holder.parent)
        }
    })
}

required init?(coder aDecoder: NSCoder) {
    fatalError("this initializer is not supported")
}

private class ToastHolder {
    let toast: Toast
    let parent: UIViewController

    init(_ t: Toast, _ p: UIViewController) {
        toast = t
        parent = p
    }
}
}

用法:

Toast("my message").show(self)

希望它能帮助某人。


1

如何使用烤面包机

乍看上去

Toast(text: "Hello, world!").show()

设置延迟和持续时间

Toast(text: "Hello, world!", duration: Delay.long)
Toast(text: "Hello, world!", delay: Delay.short, duration: Delay.long)

去除吐司

let toast = Toast(text: "Hello")
toast.show()
toast.cancel() // remove toast immediately

自定义外观

  • 背景颜色
  • cornerRadius
  • textInsets
  • textColor
  • 字形
  • bottomOffsetPortrait
  • bottomOffsetLandscape
  • shadowPath
  • shadowColor
  • shadowOpacity
  • shadowOffset
  • shadowRadius
  • maxWidthRatio
  • useSafeAreaForBottomOffset

0
static func popUp(context ctx: UIViewController, msg: String) {

    let toast = UILabel(frame:
        CGRect(x: 16, y: ctx.view.frame.size.height / 2,
               width: ctx.view.frame.size.width - 32, height: 100))

    toast.backgroundColor = UIColor.lightGray
    toast.textColor = UIColor.white
    toast.textAlignment = .center;
    toast.numberOfLines = 3
    toast.font = UIFont.systemFont(ofSize: 20)
    toast.layer.cornerRadius = 12;
    toast.clipsToBounds  =  true

    toast.text = msg

    ctx.view.addSubview(toast)

    UIView.animate(withDuration: 5.0, delay: 0.2,
        options: .curveEaseOut, animations: {
        toast.alpha = 0.0
        }, completion: {(isCompleted) in
            toast.removeFromSuperview()
    })
}

然后从UIViewController调用它

popUp(context: self, msg: "Your message")

0

让我将其添加到以下答案链中:该库完成了您需要的DCToastView,使您可以从屏幕的顶部或底部提供烤面包消息:

DCToastViewSample

您只需要添加豆荚

pod 'DCToastView'

将其导入您要使用的位置。

import DCToastView

并使用它

ToastPresenter.shared.show(in: self.view, message: "This is a toast")

您可以将以下属性传递给show方法:

  • view:将要呈现烤面包的视图
  • 消息:烤面包将显示的消息
  • toastPlace:可以是.down或.up的地方
  • backgroundColor:烤面包的背景色;默认为黑色
  • textColor:消息的文本颜色;默认为白色
  • timeOut:如果未提供烤面包,则将其解散的秒数,这意味着烤面包将变得粘稠(将保持接触直到被触摸);默认为nil
  • 圆度:烤面包有多圆:.none,.low,.mid,.high;默认为.mid

0

这将为您提供帮助,使烤面包以适当的填充物居中

func showToast(message:String,view:UIView){
    let toastLabel = PaddingLabel()
    toastLabel.frame = CGRect(x:0, y: view.frame.size.height-100, width: view.frame.width-50, height: 0)
    toastLabel.backgroundColor = UIColor.black.withAlphaComponent(0.6)
    toastLabel.textColor = UIColor.white
    toastLabel.textAlignment = .center;
    toastLabel.font = UIFont(name: "Montserrat-Light", size: 12.0)
    toastLabel.text = message
    toastLabel.alpha = 1.0
    toastLabel.layer.cornerRadius = 10;
    toastLabel.clipsToBounds  =  true
    toastLabel.sizeToFit()
    toastLabel.frame.origin.x=(view.frame.width/2)-(toastLabel.frame.width/2)
    view.addSubview(toastLabel)
    UIView.animate(withDuration: 4.0, delay: 0.1, options: .curveEaseOut, animations: {
        toastLabel.alpha = 0.0
    }, completion: {(isCompleted) in
        toastLabel.removeFromSuperview()
    })
}

并添加此PaddingLabel文件以进行标签填充

import Foundation
import UIKit
class PaddingLabel: UILabel {

let padding=UIEdgeInsetsMake(5, 10, 5,10)
override func drawText(in rect: CGRect) {
    super.drawText(in: UIEdgeInsetsInsetRect(rect, padding))
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
    let superSizeThatFits=super.sizeThatFits(size)
    let width=superSizeThatFits.width+padding.left+padding.right
    let height=superSizeThatFits.height+padding.top+padding.bottom
    return CGSize(width: width, height: height)
}
}

0

Beans先生的回答很好。但是,他的答案使用的宽度较小,并且不是多行友好的。改用它。

func showToastFaded(message : String) {


    let toastLabel = UILabel(frame: CGRect(x: self.view.frame.size.width/2 - 125, y: self.view.frame.size.height-100, width: 250, height: 35))
    toastLabel.numberOfLines = 0
    toastLabel.backgroundColor = UIColor.black.withAlphaComponent(0.6)
    toastLabel.textColor = UIColor.white
    toastLabel.textAlignment = .center;
    toastLabel.text = message
    toastLabel.alpha = 1.0
    toastLabel.layer.cornerRadius = 10;
    toastLabel.clipsToBounds  =  true
    toastLabel.sizeToFit()
    toastLabel.frame = CGRect( x: toastLabel.frame.minX, y: toastLabel.frame.minY,width:   toastLabel.frame.width + 20, height: toastLabel.frame.height + 8)

    self.view.addSubview(toastLabel)
    UIView.animate(withDuration: 4.0, delay: 0.1, options: .curveEaseOut, animations: {
        toastLabel.alpha = 0.0
    }, completion: {(isCompleted) in
        toastLabel.removeFromSuperview()
    })
}

0

您可以创建自己的烤面包风格,并将其与整个屏幕的中心对齐,如下所示:

func showToast(message: String, in viewController: UIViewController) {
        let toastContainer: UIView = {
            let view = UIView(frame: CGRect())
            view.translatesAutoresizingMaskIntoConstraints = false
            view.backgroundColor = UIColor.gray
            view.alpha = 0.0
            view.layer.cornerRadius = 12
            view.clipsToBounds = true
            return view
        }()
        let toastLabel: UILabel = {
            let label = UILabel()
            label.translatesAutoresizingMaskIntoConstraints = false
            label.text = message
            label.textColor = UIColor.white
            label.textAlignment = .center
            label.font = label.font.withSize(20)
            label.clipsToBounds = true
            label.numberOfLines = 0
            return label
        }()

        toastContainer.addSubview(toastLabel)
        viewController.view.addSubview(toastContainer)

        toastContainer.layer.zPosition = 1

        NSLayoutConstraint.activate([
            toastContainer.widthAnchor.constraint(equalToConstant: viewController.view.frame.width * 0.6),
            toastContainer.heightAnchor.constraint(equalToConstant: viewController.view.frame.height * 0.1),
            toastContainer.centerXAnchor.constraint(equalTo: viewController.view.centerXAnchor),
            toastContainer.bottomAnchor.constraint(equalTo: viewController.view.bottomAnchor, constant:
                -UIScreen.main.bounds.maxY / 2 + viewController.view.frame.height * 0.1 / 2
            ),

            toastLabel.centerXAnchor.constraint(equalTo: toastContainer.centerXAnchor),
            toastLabel.centerYAnchor.constraint(equalTo: toastContainer.centerYAnchor)
        ])

        UIView.animate(withDuration: 0.5, delay: 0.0, options: .curveEaseIn, animations: {
            toastContainer.alpha = 1.0
        }) { (_) in
            UIView.animate(withDuration: 0.5, delay: 2, options: .curveEaseOut, animations: {
                toastContainer.alpha = 0.0
            }) { (_) in
                toastContainer.removeFromSuperview()
            }
        }
    }

-1

Swift 4.2非常简单又超级

let toastLabel = UILabel()

toastLabel.lineBreakMode = .byWordWrapping
toastLabel.numberOfLines = 0
toastLabel.text = "Type your message you want to show in toast"
toastLabel.sizeToFit()
//MARK Resize the Label Frame
toastLabel.frame = CGRect(x: toastLabel.frame.origin.x, y: toastLabel.frame.origin.y, width: toastLabel.frame.size.width + 40, height: toastLabel.frame.size.height + 40)
self.view.addSubview(toastLabel)
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.