0

I want to toggle the blur effect on top of an image I have on my iOS8 app. I know that from the basic idea of this if/else implementation is wrong, but I've got no clue how to do it correctly since I'm new to this. Any recomendation would be gladly accepted.

I'd also like to toggle text on top of the blurred image.

I've got this global constant in my view controller

var cont: Int = 0

And here is the @IBAction related to a button on top of my image.

@IBAction func moreInfo(){

    /* First, create the blur effect with the "Dark" style.
    All the styles are defined in UIBlurEffectStyle */
    let blurEffect = UIBlurEffect(style: .Dark)

    /* Then create the effect view, using the blur effect that
    we just created. The effect is of type UIVisualEffect */
    let blurView = UIVisualEffectView(effect: blurEffect)
    blurView.frame.size = CGSize(width: 200, height: 250)
    blurView.center = CGPoint(x: 160, y: 250)


    /* Toggle blur*/
    if (cont == 0){

        view.addSubview(blurView)
    } else {

        /* view.removeFromSuperview(blurView)??? */ //Here should be a way to remove the blur


    }


}
4

1 回答 1

1

removeFromSuperview() needs the previous blurView.

The answer which most closely matches your code is add something like savedBlurView to save the blur view between calls.

var cont: Int = 0
var savedBlurView: UIVisualEffectView?

@IBAction func moreInfo() {
    /* First, create the blur effect with the "Dark" style.
    All the styles are defined in UIBlurEffectStyle */
    let blurEffect = UIBlurEffect(style: .Dark)

    /* Then create the effect view, using the blur effect that
    we just created. The effect is of type UIVisualEffect */
    let blurView = UIVisualEffectView(effect: blurEffect)
    blurView.frame.size = CGSize(width: 200, height: 250)
    blurView.center = CGPoint(x: 160, y: 250)

    if (cont == 0) {
        view.addSubview(blurView)
        savedBlurView = blurView
    } else {
        savedBlurView?.removeFromSuperview()
        savedBlurView = nil
    }
}

This logic is a bit rough and can be cleaned up.

var isBlurred: Bool = false
var savedBlurView: UIVisualEffectView?

@IBAction func moreInfo() {
    if !isBlurred {
        let blurEffect = UIBlurEffect(style: .Dark)
        let blurView = UIVisualEffectView(effect: blurEffect)
        blurView.frame.size = CGSize(width: 200, height: 250)
        blurView.center = CGPoint(x: 160, y: 250)

        view.addSubview(blurView)
        savedBlurView = blurView
        isBlurred = true
    } else {
        savedBlurView?.removeFromSuperview()
        savedBlurView = nil
        isBlurred = false
    }
}

Here I use a boolean to test is I need to blur, I only create the blur effect when it's needed and I update the boolean at the point I'm changing state.

于 2014-10-12T00:05:40.133 回答