将UIImageView设置为模糊的初始状态

时间:2017-03-30 03:14:29

标签: ios swift uiimageview uivisualeffectview uiblureffect

我试图在UIViewController上初始模糊背景图片。当@IBAction被调用时,我想要取消backgroundImage。我可以让图像初始模糊,但如果我最初模糊它,我就无法摆脱模糊。但是,如果我最初没有模糊backgroundImage,我的方法可以在模糊和不模糊的图像之间切换。

这些是我UIViewController班的相关变量。

@IBOutlet weak var backgroundImage: UIImageView!
// I also leave this hanging around so I can add/remove it as needed
var blurView = UIVisualEffectView(effect: UIBlurEffect(style: .light))

加载视图时,我最初希望backgroundImage对其进行UIVisualEffectView。我最初尝试在toggleBlurView中拨打viewDidLoad,但UIBlurEffect的显示已关闭,因此我在toggleBlurView中添加了viewDidLayoutSubviews的代码,那个问题。

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    // if I comment this out, the toggleBlurView() method works as desired
    toggleBlurView()
}

这是我的toggleBlurView方法。

func toggleBlurView() {
    // if there's a blurView, remove it...
    if blurView.isDescendant(of: backgroundImage) {
        blurView.removeFromSuperview()
    } 
    // otherwise, add blurView to backgroundImage
    else {
        blurView = UIVisualEffectView(effect: UIBlurEffect(style: .light))
        blurView.frame = backgroundImage.bounds
        backgroundImage.addSubview(blurView)
    }
}

我有一个@IBAction,在调用时,也会运行toggleBlurView方法。

@IBAction func playFrequency(_ sender: UIButton) {
    // do stuff
    toggleBlurView()
}

我的代码没有崩溃,但我无法获得所需的结果。我不确定我是否发现了错误或我做错了什么。我打赌后者。感谢您阅读,我欢迎您建议如何将图像设置为模糊的初始状态。

1 个答案:

答案 0 :(得分:1)

我按照您的意愿使用了以下代码。我更改了toggleBlurView功能,因此它更灵活,但这不会影响功能。

//
//  ViewController.swift
//  tableviewheader-test
//
//  Created by Forest Kunecke on 3/29/17.
//  Use this code for freeeeee!!!!  Free as in free beer!!
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var myImage: UIImageView!
    var blurView = UIVisualEffectView(effect: UIBlurEffect(style: .light))

    override func viewDidLoad() {
        super.viewDidLoad()

        toggleBlurView(myImage)
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    @IBAction func toggleBlur(_ sender: Any) {
        toggleBlurView(myImage)
    }

    func toggleBlurView(_ imageView: UIImageView) {
        // if there's a blurView, remove it...
        if blurView.isDescendant(of: imageView) {
            blurView.removeFromSuperview()
        }
            // otherwise, add blurView to backgroundImage
        else {
            blurView = UIVisualEffectView(effect: UIBlurEffect(style: .light))
            blurView.frame = imageView.bounds
            imageView.addSubview(blurView)
        }
    }

}

以下是我的故事板的截图:

screenshot of toggle image storyboard