gpt4 book ai didi

swift - 在 swift iOS8 中切换 UIBlurEffect

转载 作者:行者123 更新时间:2023-11-30 10:21:31 27 4
gpt4 key购买 nike

我想在 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com