模糊效果 – 背景UITextField

我使用Swift 2和Xcode 7。

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

我本来想在后台添加一个视图。 但我不知道如何制作UITextField。

你有解决方案吗 ?

您只能添加某种视图才能使其成为模糊视图。 现在的问题是textfields没有backgroundView属性,但它们有一个background属性,我们可以在其中设置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) } 

对于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) } 

这是附带的截图

在此处输入图像描述

希望这可以帮助

你有解决方案吗?

您始终可以将透明文本字段放在另一个视图的顶部 。 如果该视图恰好与文本字段具有相同的大小,则它看起来就像文本字段的背景视图。 您甚至可以将文本字段设置为“背景”视图的子视图,以便您可以更轻松地将它们移动到一起。

您可以将背景颜色设置为白色,并更改其Alpha值:

 myTextField.alpha = 0.5; 

可能不完全是你问的,但更容易实现。