具有内部阴影的自定义圆形文本字段无法获得正确的布局

时间:2019-02-25 19:13:38

标签: swift xcode uiview calayer uibezierpath

我想创建一个带有嵌入式阴影的文本字段。

我找到了答案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)
}

如何编辑代码,以使文本字段再次在屏幕上正确缩放?

1 个答案:

答案 0 :(得分:0)

关键是在哪里调用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定义中)也可以有所改善。