我使用 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+ 的 UIBlurEffect
和 UIVisualEffectView
//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)
}
附上截图
希望对你有帮助
关于ios - 模糊效果 - 背景 UITextField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34188042/