如何使用swift在应用程序委托函数中使用toast方法

如何使用swift在应用程序委托函数中使用toast方法,swift,swift2,appdelegate,toast,Swift,Swift2,Appdelegate,Toast,您好,我正在我的应用程序中使用swift开发应用程序。我想使用toast消息和toast活动,所以我按照链接:。我可以使用视图中的控制器方法,它工作得很好,但我不能使用应用程序中的委托方法 我的应用程序代理中的我的代码: func loadJsonData(){ self.view.makeToastActivity(.center) } 上面提到的代码不起作用,因为app delegate没有成员视图…请帮助我在我的app delegate中使用该视图。请尝试此操作,通过此操作

您好,我正在我的应用程序中使用swift开发应用程序。我想使用toast消息和toast活动,所以我按照链接:。我可以使用视图中的控制器方法,它工作得很好,但我不能使用应用程序中的委托方法

我的应用程序代理中的我的代码:

func loadJsonData(){

    self.view.makeToastActivity(.center) 

}

上面提到的代码不起作用,因为app delegate没有成员视图…请帮助我在我的app delegate中使用该视图。

请尝试此操作,通过此操作您可以获得应用程序的顶级控制器,然后您可以在顶级控制器上添加toast

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

AppDelegate用于处理初始化应用程序、关闭应用程序、通知等事项

您要做的是:

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

import UIKit

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

注意:请确保保存FirstView.swift文件,否则此文件将无法使用。

改为定制的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

})



}
无论何时激活上一个函数,它都会呈现类似的内容


为什么不在app delegate中使用窗口实例?app delegate窗口对象也有一个view属性。如何使用窗口制作toast您能给出一些示例吗?我刚刚使用了self.window?.currentViewController()?.view.makeToastActivity(.Center)…很有效谢谢您有额外的
窗口后…最好安全地打开它。也许这个方法会在应用程序处于后台时调用,即没有窗口(如图所示),并且会使应用程序崩溃…非常好,唯一的一点是我认为toast消息通常不会随着时间的推移被动画化。必须有一些东西触发它,如网络是否再次连接或位置访问是否再次工作等。确定原因,请在appdelegate中添加后台侦听器以监视网络可访问性,一旦网络不可用,请在我的情况下渲染您的个人和自定义toast,甚至动画。