swift - 在 swift iOS8 中切换 UIBlurEffect

标签 swift ios8 uiblureffect

我想在 iOS8 应用程序上的图像顶部切换模糊效果。我知道从这个 if/else 实现的基本思想来看是错误的,但我不知道如何正确地做到这一点,因为我是新手。任何建议都会很乐意接受。

我还想在模糊图像之上切换文本。

我的 View Controller 中有这个全局常量

var cont: Int = 0

这是与我的图像顶部的按钮相关的@IBAction。

@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


    }


}

最佳答案

removeFromSuperview() 需要之前的 blurView

与您的代码最匹配的答案是添加类似 savedBlurView 的内容来保存调用之间的模糊 View 。

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
    }
}

这个逻辑有点粗糙,可以清理一下。

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
    }
}

这里我使用 bool 值来测试是否需要模糊,我仅在需要时创建模糊效果,并在更改状态时更新 bool 值。

关于swift - 在 swift iOS8 中切换 UIBlurEffect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26320339/

相关文章:

ios - TextInpout 自动更正在 ios 中显示相反 [react native]

swift - 为什么改变 Actor 的 nonSendable 属性是合法的?

javascript - 使用第三方 IME 时,JS keydown keyup keypress 事件在 IOS8 上不起作用

swift - 如何将 UIVibrancyEffect 添加到现有的 UILabel ( IBOutlet )?

ios - 如何使用 Swift 将模糊效果添加到 UIImage 中?

ios - 在 Swift 中使用泛型重载包装函数

Swift:完成处理程序和单例

core-data - 使用谓词在结果中搜索

ios - 如何在不创建 CLLocationManager 实例的情况下请求位置授权?

ios - 在swift中设置模糊效果全屏