如何在圆角的UITextField上添加阴影?
我想实现一个阴影UITextField
圆角像下面的图像:如何在圆角的UITextField上添加阴影?
我的代码如下:
override func viewDidLoad() {
super.viewDidLoad()
textField.layer.cornerRadius = textField.frame.size.height/2
textField.layer.borderWidth = 1.0
textField.layer.borderColor = UIColor(white: 0.5, alpha: 0.3).cgColor
textField.layer.shadowOpacity = 1
textField.layer.shadowRadius = 4.0
textField.layer.shadowColor = UIColor.black.cgColor
}
,但是,我觉得缺了点什么......
在此先感谢!
尝试下面的代码实现对roundRect
文本框的阴影效果。
//Basic texfield Setup
textField.borderStyle = .none
textField.backgroundColor = UIColor.groupTableViewBackground // Use anycolor that give you a 2d look.
//To apply corner radius
textField.layer.cornerRadius = textField.frame.size.height/2
//To apply border
textField.layer.borderWidth = 0.25
textField.layer.borderColor = UIColor.white.cgColor
//To apply Shadow
textField.layer.shadowOpacity = 1
textField.layer.shadowRadius = 3.0
textField.layer.shadowOffset = CGSize.zero // Use any CGSize
textField.layer.shadowColor = UIColor.gray.cgColor
//To apply padding
let paddingView : UIView = UIView(frame: CGRect(x: 0, y: 0, width: 20, height: textField.frame.height))
textField.leftView = paddingView
textField.leftViewMode = UITextFieldViewMode.always
注:出于某种原因textField.borderStyle = .none
未生效,即使设置代码viewWillLayoutSubviews()
或viewDidLayoutSubviews()
。所以,我建议你通过故事板文本框Attributes inspector
设置的borderStyle。从实际设备
输出:
为了实现阴影效果:(像其他SO
帖)
textField.layer.borderColor = UIColor.black.withAlphaComponent(0.25).cgColor
textField.layer.shadowOffset = CGSize(width: 0, height: 3)
textField.layer.shadowColor = UIColor.black.cgColor //Any dark color
输出:
很棒!谢谢你! –
试试这个:
textField.layer.masksToBounds = false
textField.layer.shadowRadius = 4.0
textField.layer.shadowColor = UIColor.black.cgColor
textField.layer.shadowOffset = CGSize(width: 1.0, height: 1.0)
textField.layer.shadowOpacity = 1.0
您可以添加此扩展名,然后使用方法“addShadow”到阴影添加到您文本字段,标签,TextView的等..
extension UIView {
func addShadow(shadowColor: CGColor = UIColor.black.cgColor,
shadowOffset: CGSize = CGSize(width: 1.0, height: 2.0),
shadowOpacity: Float = 0.4,
shadowRadius: CGFloat = 3.0) {
layer.shadowColor = shadowColor
layer.shadowOffset = shadowOffset
layer.shadowOpacity = shadowOpacity
layer.shadowRadius = shadowRadius
layer.masksToBounds = false
}
}
不工作,因为maskToBound属性为true。 –
使用这下面的代码
textfield.layer.cornerRadius = textfield.frame.size.height/2
textfield.clipsToBounds = false
textfield.layer.shadowOpacity=0.4
textfield.layer.shadowOffset = CGSize(width: 0, height: 0)
输出:
其显示textfield的外行...检查我的输出。 –
@UdayBabariya删除边框宽度和颜色,并使用textfield白色,并在textfield后面查看白色,以便您可以清晰地查看。 –
这增加了** **边界,而不是一个影子。 – the4kman
yaa ..但如何添加阴影?? @ the4kman –
[UITextField文字上的阴影]可能的重复(https://stackoverflow.com/questions/1274168/drop-shadow-on-uitextfield-text) –