gpt4 book ai didi

swift - 带有内部阴影的自定义圆形文本字段未获得正确的布局

转载 作者:行者123 更新时间:2023-11-30 10:49:45 25 4
gpt4 key购买 nike

我想制作一个带有插入阴影的文本字段。

我找到了答案here但我没有得到预期的结果,因为我没有足够的业力,无法发表评论。

这是我得到的结果:

enter image description 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。加载 View 时,它通常具有从 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 定义中)来改进它。

关于swift - 带有内部阴影的自定义圆形文本字段未获得正确的布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54873171/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com