如何在alertcontroller存在时模糊viewcontroller?

时间:2016-07-27 18:39:07

标签: swift uialertcontroller

有可能这样做吗?我有一个UIAlertController出现在一个viewcontroller中。我希望实现的是当警报出现时模糊/覆盖背景,一旦警报消失,背景应该是可见的

导入UIKit 导入LocalAuthentication class TabBarViewController:UITabBarController {

@IBOutlet weak var noteTabBar: UITabBar!

override func viewDidLoad() {
super.viewDidLoad()
    self.authenticateUser()
    self.tabBar.hidden = false
    self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())

    let userDefaults = NSUserDefaults.standardUserDefaults()
    userDefaults.setObject(false, forKey: "sendModeToggle")
    userDefaults.setObject("Avenir-Medium", forKey: "font")
     userDefaults.setObject(13, forKey:"fontSize")
            // Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}
*/

// MARK: Touch ID Authentication

func authenticateUser()
{
    let context = LAContext()
    var error: NSError?
    let reasonString = "Authentication is needed to access your app! :)"

    let blurEffect = UIBlurEffect(style: .Light)
    let blurVisualEffectView = UIVisualEffectView(effect: blurEffect)
    blurVisualEffectView.frame = view.bounds

    if context.canEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, error: &error)
    {

        context.evaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, localizedReason: reasonString, reply: { (success, policyError) -> Void in

            if success
            {
                print("Authentication successful! :) ")
                blurVisualEffectView.removeFromSuperview()

            }
            else
            {
                switch policyError!.code
                {
                case LAError.SystemCancel.rawValue:
                    print("Authentication was cancelled by the system.")
                /*case LAError.UserCancel.rawValue:
                    print("Authentication was cancelled by the user.")
                 */   
                case LAError.UserFallback.rawValue:
                    print("User selected to enter password.")
                    NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
                        self.showPasswordAlert()
                    })
                default:
                    print("Authentication failed! :(")
                    NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
                        self.showPasswordAlert()
                    })
                }
            }

        })
    }
    else
    {
        print(error?.localizedDescription)
        NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
            self.showPasswordAlert()
        })
    }


}

// MARK: Password Alert

func showPasswordAlert()
{

    let blurEffect = UIBlurEffect(style: .Light)
    let blurVisualEffectView = UIVisualEffectView(effect: blurEffect)
    blurVisualEffectView.frame = view.bounds


    let alertController = UIAlertController(title: "Touch ID Password", message: "Please enter your password.", preferredStyle: .Alert)

    let defaultAction = UIAlertAction(title: "OK", style: .Cancel) { (action) -> Void in

        if let textField = alertController.textFields?.first as UITextField?
        {
            if textField.text == "notes"
            {
                print("Authentication successful! :) ")
                blurVisualEffectView.removeFromSuperview()
            }
            else
            {
                self.showPasswordAlert()

            }
        }
    }
    alertController.addAction(defaultAction)

    alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in

        textField.placeholder = "Password"
        textField.secureTextEntry = true
    }
    self.view.addSubview(blurVisualEffectView)
    self.presentViewController(alertController, animated: true, completion: nil)
}

}

5 个答案:

答案 0 :(得分:7)

UIAlertController背景显示为模糊使用UIVisualEffectView

 let blurEffect = UIBlurEffect(style: .Light)
 let blurVisualEffectView = UIVisualEffectView(effect: blurEffect)
 blurVisualEffectView.frame = view.bounds

 let alertController = UIAlertController.init(title: "Title", message: "Message", preferredStyle: .Alert)

 alertController.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in
     print("Handle Ok logic here")
     blurVisualEffectView.removeFromSuperview()
 }))

 alertController.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { (action: UIAlertAction!) in
     print("Handle Cancel Logic here")
     blurVisualEffectView.removeFromSuperview()
 }))
 self.view.addSubview(blurVisualEffectView)
 self.presentViewController(alertController, animated: true, completion: nil)

<强>截图

显示警报视图之前显示警报视图时

enter image description here enter image description here

答案 1 :(得分:2)

您可以在UIVisualEffectView出现时向viewController view媒体资源添加alert,并在{{1}时删除此blurView被解雇了。

alert

当您var blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark) var blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.frame = view.bounds blurEffectView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] // for supporting device rotation view.addSubview(blurEffectView) 被解雇时,请致电alert

答案 2 :(得分:1)

在swift 3.1中

    let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light)
    let blurEffectView = UIVisualEffectView(effect: blurEffect)
    blurEffectView.frame = view.bounds
    blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    self.view.addSubview(blurEffectView)

    let previewController = UIAlertController(title: "Following", message: "Hello", preferredStyle: .alert)

    let followAction = UIAlertAction(title: "Follow", style: .default, handler: { (UIAlertAction) in
        blurEffectView.removeFromSuperview()
    })

    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: { (UIAlertAction) in
        blurEffectView.removeFromSuperview()
    })

    previewController.addAction(cancelAction)
    previewController.addAction(followAction)

    present(previewController, animated: true, completion: nil)

答案 3 :(得分:0)

您可以通过创建一个具有透明背景和UIVisualEffectView的模态视图控制器来完成此操作。让它出现在当前视图控制器的上下文中,然后让它显示警报。

这样,视图控制器会在呈现警报之前模糊当前视图。

答案 4 :(得分:0)

使用UIVisualEffectView将视图设置为内容的掩码,然后在模糊视图的顶部添加警报。

这是一个例子

private var _blurView: UIVisualEffectView?

然后在你的课堂内

func layoutBlurView(){
    if(self._blurView == nil){
        let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Light)
        self._blurView = UIVisualEffectView(effect: blurEffect)
        self.view.insertSubview(self._blurView!, belowSubview: alertView)
    }
    self._blurView!.frame = self.view.bounds
}

其中alertView是....您的警报视图