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