【问题标题】:Toggle UIBlurEffect in swift iOS8在 swift iOS8 中切换 UIBlurEffect
【发布时间】:2014-10-11 23:32:27
【问题描述】:

我想在我的 iOS8 应用上的图像上切换模糊效果。我知道从这个 if/else 实现的基本思想是错误的,但我不知道如何正确地做到这一点,因为我是新手。任何建议都将被欣然接受。

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

我的视图控制器中有这个全局常量

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


    }


}

【问题讨论】:

    标签: swift ios8 uiblureffect


    【解决方案1】:

    removeFromSuperview() 需要之前的blurView

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

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

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

    【讨论】:

    • 感谢它按我想要的方式工作。你有什么好的 swift 教程,顺便说一句,你可以推荐我吗?我想用 rails api 制作一个社交/电子商务应用程序,但发现自己对在 JSON 请求中激活查询的选项卡感到困扰。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-21
    • 1970-01-01
    相关资源
    最近更新 更多