我有一个可重用的alertController组件,用于在整个应用程序中创建一个alertController。我试图添加一个模糊的效果,但我不能引用的观点,alertController总是在顶部。
let blurEffect = UIBlurEffect(style: .light)
let blurVisualEffectView = UIVisualEffectView(effect: blurEffect)
blurVisualEffectView.frame = self.view.bounds
let vc = UIAlertController(title: title, message: message, preferredStyle: .alert)
let alertActions = (actions.map { a in UIAlertAction(title: a.display, style: .default, handler: { _ in then() ; a.handler?() }) })
for action in alertActions {
vc.addAction(action)
blurVisualEffectView.removeFromSuperview()
}
if actions.isEmpty {
let action = UIAlertAction(title: "Something went wrong", style: .default) { _ in then() }
vc.addAction(action)
}
self.view.addSubview(blurVisualEffectView)我所犯的错误是
未解析标识符'self‘的使用
发布于 2019-10-03 16:13:08
你需要
extension UIViewController {
func showBluredAlert(_ actions:[Model]) {
let blurEffect = UIBlurEffect(style: .light)
let blurVisualEffectView = UIVisualEffectView(effect: blurEffect)
blurVisualEffectView.frame = self.view.bounds
self.view.addSubview(blurVisualEffectView)
// add the alert here
}
}然后在任何vc实例中调用
showBluredAlert(<#[Model]#>)也别忘了这句话
self.present(vc, animated: true, completion: nil)发布于 2019-10-03 16:21:16
我要做的是使用Notification。Notification允许应用程序的不同部分相互通信。首先,在警报控制器创建的任何类中添加一个观察者:
class myClass: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(showAlertController), name: "ShowAlertController", object: nil)
}
@objc func showAlertController() {
//Within this function, add the code that will show the alert controller
}
}现在,从应用程序中的任何其他视图控制器中,您可以发布到名为"ShowAlertController“的ShowAlertController,这个showAlertController()方法将被调用:
class someViewController {
//Pressing this button should make the alert controller appear
@IBAction buttonPressed(_ sender: Any) {
NotificationCenter.default.post(name: "ShowAlertController", object: nil)
}
}很难说这种方法对您有用,因为我不确定您提供的代码是在什么上下文中使用的,但是假设您有某种包含视图控制器(其中包含了其他视图控制器),那么这种方法应该适用于您。
理想情况下,您可能希望像Sh_Khan建议的那样对Sh_Khan进行扩展,但是如果必须在一个类中引用另一个类的方法,Notification是一个解决方案。
发布于 2019-10-03 18:38:06
每个视图控制器都有对其父级的引用。如果您想要父viewController的视图,它的parent?.view。此外,每个模态都可以得到它的presentingViewController。不过,我只想将模糊的内容添加到警报控制器的视图中,因为处理另一个您不拥有的对象的内部结构通常是不好的:
vc.view.addSubview(blurVisualEffectView)https://stackoverflow.com/questions/58223018
复制相似问题