长时间的监听者,第一次的调用者..
我正在尝试将横幅添加到我的应用中,该横幅在没有网络连接时会显示。我的应用程序使用了大约9个视图控制器,因此我认为UIViewcontroller的扩展将是一个明智的起点。我有一些逻辑来检查网络的运行状况,然后基于失败,它会驱动NotificationCenter.post在当前显示器上显示viewController。这段代码位于UIViewController扩展中,用于显示屏幕-似乎起作用:
func showNoNetworkBanner()
{
if let theMask = parent?.view.viewWithTag(666) {
return // already setted..
} else {
let maskView = UIView()
maskView.tag = 666
maskView.backgroundColor = UIColor.lightGray
let vc = self.storyboard?.instantiateViewController(withIdentifier: "vc_NotNetworkWarning") as! vc_NotNetworkWarning
maskView.addSubview(vc.view)
parent?.view.addSubview(maskView)
}
}
另一方面,当视图控制器出现时,视图控制器中会运行一些代码以查看运行状况是否正常。如果健康状况良好,它将使视图控制器消失。在视图控制器中,我几乎尝试了所有操作。当我使用此代码时,视图控制器永远不会消失。
let vc = parent?.view.viewWithTag(666)
vc?.removeFromSuperview()
我尝试过的另一种变化是使用.removeFrom ParentViewController()并且ViewController确实消失了,但是随后我的调用它的代码不起作用,因为viewWithTag(666)始终返回true。
self.removeFromParentViewController()
有人可以帮我吗?是否有更好的方法在任何视图控制器上显示单个“横幅”?
谢谢!
答案 0 :(得分:0)
晚上好。
根据您的问题,我认为您正在进行网络连接检查,因为它应该工作。我将以以下方式显示横幅:
使用包含以下代码的新.swift文件创建横幅:
class BannerViewLauncher: NSObject {
var viewController: UIViewController?
lazy var bannerView : UIView = {
let view = UIView(frame: .zero)
view.backgroundColor = .lightGray
return view
}()
//create more UIelements if you want to design the banner further. don't forget to add them as subviews to the bannerView and give them constraints.
func showNoNetworkBanner() {
if let window = UIApplication.shared.keyWindow {
window.addSubview(bannerView)
//define your desired size here (y position is out of view so it is off view by default, the y position will be changed when you call the showNoNetworkBanner() method.
bannerView.frame = CGRect(x: 0, y: -100, width: window.frame.width, height: 100)
//change withDuration if you want it to display slower or faster, just change all of them to the same for it so look good
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseInOut, animations: {
self.bannerView.frame = CGRect(x: 0, y: -100, width: window.frame.width, height: 100)
}, completion: nil)
}
}
func hideNoNetworkBanner() {
if let window = UIApplication.shared.keyWindow {
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseIn, animations: {
self.bannerView.frame = CGRect(x: 0, y: -100, width: window.frame.width, height: 100)
}, completion: nil)
}
}
}
在ViewController中,您想显示BannerViewLauncher
的这个(一个或多个)子类,并按NoNetwork观察器方法触发时所述的那样调用方法。
lazy var bannerViewLauncher : BannerViewLauncher = {
let launcher = BannerViewLauncher()
launcher.viewController = self
return launcher
}()
//call the following when you want the banner to display
bannerViewLauncher.showNoNetworkBanner()
//call this when you want to hide the banner
bannerViewLauncher.hideNoNetworkBanner()
希望这能回答您的问题。