【问题标题】:How to use toast method in app delegate functions using swift如何使用 swift 在应用程序委托函数中使用 toast 方法
【发布时间】:2017-01-06 13:02:09
【问题描述】:

嗨,我在我的应用程序中使用 swift 开发应用程序我想使用 toast 消息和 toast 活动,所以我点击了链接:https://github.com/scalessec/Toast-Swift。我可以在视图控制器方法中使用它工作得很好,但我不能在应用程序委托方法中使用。

我的应用委托中的代码:

func loadJsonData(){

    self.view.makeToastActivity(.center) 

}

上述代码不起作用,因为应用代理没有成员视图...请帮助我在我的应用代理中使用它。

【问题讨论】:

  • 为什么不在应用委托中使用窗口实例?
  • 在App委托窗口对象也有一个view属性。
  • 如何使用window制作吐司可以举个例子

标签: swift swift2 appdelegate toast


【解决方案1】:

AppDelegate 用于处理初始化应用、关闭应用、通知等事情。

你想做的是:

  • 转到情节提要(名为 Main.storyboard)
  • 将 ViewController 添加到情节提要 (drag it from the bottom right)
  • 例如,创建一个 Swift 文件并将其命名为 FirstView,然后添加以下代码

FirstView.swift

import UIKit

class FirstView: UIViewController
{
    override func viewDidLoad()
    {
        self.view.makeToastActivity(.center);
    }
}
  • 返回故事板
  • 点击刚刚创建的 ViewController
  • 看一下屏幕右上角,会有六个小图标。单击左侧的三分之一,然后在名为“Class”的第一个字段中键入 FirstView (see attached picture)。

注意:确保保存 FirstView.swift 文件,否则这将不起作用。

【讨论】:

    【解决方案2】:

    来个定制的 Toast 怎么样?一个更具吸引力、适合您的需求且不需要库或复杂含义的版本?

    现在让我们试试下面的代码

     func  sailAwayLabelAction(){
    
        // here creating a rectangle with certain dimensions you can easily manipulate 
        let rect = CGRect(origin: CGPoint(x: self.view.frame.size.width/2 - 150,y :self.view.frame.size.height-100), size: CGSize(width: 300, height: 35))
    
    
    //here creating and manipulating the attributes of your text, i.e color,alignment etc..
    let toastLabel = UILabel(frame: rect)
    toastLabel.backgroundColor = UIColor.orange
    toastLabel.textColor = UIColor.white
    toastLabel.textAlignment = NSTextAlignment.center;
    toastLabel.text = "This is my customized Toast !"
    toastLabel.layer.cornerRadius = 10;
    toastLabel.clipsToBounds  =  true
    
    //first pop the toast into our view 
    self.view.addSubview(toastLabel)
    
    //then after 1 sec + 1 sec delay, animate the entire toastLabel out.
    UIView.animate(withDuration: 1, delay: 1, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
    
        toastLabel.alpha = 0.0
    
    })
    
    
    
    }
    

    当你激活之前的函数时,它应该呈现类似这样的东西,

    【讨论】:

    • 非常好,唯一的一点是我认为 toast 消息通常不会随着时间的推移而被动画化。必须触发它,例如您的网络是否再次连接或您对位置的访问是否再次正常等等。
    • 确定为什么不这样做,在 appdelegate 中添加后台监听器以监控网络可访问性,一旦网络不可用,在我的情况下呈现您的个人和自定义吐司甚至动画。
    【解决方案3】:

    请试试这个,通过这个你可以得到你应用的顶级控制器,然后你可以在顶级控制器上添加吐司

    let win:UIWindow = UIApplication.shared.delegate!.window!!
    win.currentViewController()?.view
    

    【讨论】:

    • 我刚刚使用了 self.window?.currentViewController()?.view.makeToastActivity(.Center).. 它工作得很好,谢谢
    • window 后面有一个额外的!...而且最好安全地打开它。也许当应用程序在后台时调用此方法,即没有窗口(如图here)并且会使应用程序崩溃......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多