ios - 模糊效果 - 背景 UITextField

标签 ios swift uitextfield uiblureffect

我使用 Swift 2 和 Xcode 7。

我想模糊我的 UITextField 的背景。我没有找到属性 backgroundView。仅 background(用于背景图像)或 backgroundColor

我会在后台添加一个 View 。但我不知道如何制作 UITextField。

你有解决办法吗?

最佳答案

您只能添加某种 View ,使其成为模糊 View 。现在的问题是文本字段没有 backgroundView 属性,但它们确实有一个背景属性,我们可以在其中设置 UIImage。所以我们也可以从 UIView 制作一个 UIImage

此方法将为传递的 UIView 创建一个 UIImage。

func imageWithView(view:UIView)->UIImage{
        UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0.0)
        view.layer.renderInContext(UIGraphicsGetCurrentContext()!)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }

现在我们将使用适用于 iOS 8+ 的 UIBlurEffectUIVisualEffectView

//only apply the blur if the user hasn't disabled transparency effects
if !UIAccessibilityIsReduceTransparencyEnabled() {
    let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Light) 
    //you can try for more values like .ExtraLight and .Dark

    let blurEffectView = UIVisualEffectView(effect: blurEffect)
    blurEffectView.frame = textField.bounds
    blurEffectView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
    textField.backgroundColor = UIColor.clearColor()

    //Set the blurred image made from blurred view as textfield's background
    textField.background = imageWithView(blurEffectView)
}

For Swift 3.0

func imageWithView(view:UIView)->UIImage {
       UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0.0)
       view.layer.render(in: UIGraphicsGetCurrentContext()!)
       let image = UIGraphicsGetImageFromCurrentImageContext()
       UIGraphicsEndImageContext()
       return image!
}

if !UIAccessibilityIsReduceTransparencyEnabled() {
    let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light)
    //you can try for more values like .extraLight and .dark

    let blurEffectView = UIVisualEffectView(effect: blurEffect)
    blurEffectView.frame = textField.bounds
    blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    textField.backgroundColor = UIColor.clear

    //Set the blurred image made from blurred view as textfield's background
    textField.background = imageWithView(view: blurEffectView)
}

附上截图

enter image description here

希望对你有帮助

关于ios - 模糊效果 - 背景 UITextField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34188042/

相关文章:

ios - Swift PageView 滚动后最新图像的一部分保留在边框中

ios - 在输入击键时获取 UITextField 的值?

IOS 13 : spacing Issue with UITextField rightView

ios - 台风 + swift : Crash when using run-time arguments

ios - 第三方开发人员在企业内发布的iOS应用

ios - 解析 JSON 并使用 Realm 保存

ios - 更新使用数据库的应用程序

swift - 在 Swift 中转换为不同的 C 结构不安全指针

ios - 如何使用 Daniel Gindis 图表库在同一轴上绘制相同类型的图表(在折线图中)?

swift - 如何在 Swift 3.0 的 UITextField 中隐藏菜单中的粘贴选项?