我想制作一个插入阴影的文本字段。
我找到了答案here,但我没有得到预期的结果,因为我没有足够的业力,不能发表评论。
这是我得到的结果:
这是代码:
func applyDesign() {
let innerShadow = CALayer()
innerShadow.frame = bounds
// Shadow path (1pt ring around bounds)
let radius = self.frame.size.height/2
let path = UIBezierPath(roundedRect: innerShadow.bounds.insetBy(dx: -1, dy:-1), cornerRadius:radius)
let cutout = UIBezierPath(roundedRect: innerShadow.bounds, cornerRadius:radius).reversing()
path.append(cutout)
innerShadow.shadowPath = path.cgPath
innerShadow.masksToBounds = true
// Shadow properties
innerShadow.shadowColor = UIColor.darkGray.cgColor
innerShadow.shadowOffset = CGSize(width: 0, height: 2)
innerShadow.shadowOpacity = 0.5
innerShadow.shadowRadius = 2
innerShadow.cornerRadius = self.frame.size.height/2
layer.addSublayer(innerShadow)
}
如何编辑代码以便文本字段再次正确缩放屏幕?
关键是你在哪里调用applyDesign。加载视图时,它通常具有从nib / init方法派生的大小。因此,如果您应用设计,它可能与以后的屏幕上的内容不匹配。
在您的情况下,每次文本字段由自动布局引擎布置时,您应该重新应用这些自定义设计。
简短的例子它看起来如何:
class CustomField: UITextField {
lazy var innerShadow: CALayer = {
let innerShadow = CALayer()
layer.addSublayer(innerShadow)
return innerShadow
}()
override func layoutSubviews() {
super.layoutSubviews()
applyDesign()
}
func applyDesign() {
innerShadow.frame = bounds
// Shadow path (1pt ring around bounds)
let radius = self.frame.size.height/2
let path = UIBezierPath(roundedRect: innerShadow.bounds.insetBy(dx: -1, dy:-1), cornerRadius:radius)
let cutout = UIBezierPath(roundedRect: innerShadow.bounds, cornerRadius:radius).reversing()
path.append(cutout)
innerShadow.shadowPath = path.cgPath
innerShadow.masksToBounds = true
// Shadow properties
innerShadow.shadowColor = UIColor.darkGray.cgColor
innerShadow.shadowOffset = CGSize(width: 0, height: 2)
innerShadow.shadowOpacity = 0.5
innerShadow.shadowRadius = 2
innerShadow.cornerRadius = self.frame.size.height/2
}
}
你可以通过将一些冗余设置从applyDeisgn
移动到某种一次性初始化器来改进它(即使在这个懒惰的var定义中)。