UITextField中的内部阴影带圆角

iOS*_*eek 5 shadow uitextfield ios swift

我想实现这个UITextField设计:

在此输入图像描述

在Zeplin中,这里是阴影的属性:

在此输入图像描述

我试过了什么?

override func layoutSubviews() {
    super.layoutSubviews()
    self.layer.cornerRadius = self.frame.size.height/2
    self.addInnerShadow()
}


private func addInnerShadow() {
    let innerShadow = CALayer()
    innerShadow.frame = bounds
    // Shadow path (1pt ring around bounds)
    let path = UIBezierPath(rect: innerShadow.bounds.insetBy(dx: -1, dy: -1))
    let cutout = UIBezierPath(rect: innerShadow.bounds).reversing()
    path.append(cutout)
    innerShadow.shadowPath = path.cgPath
    innerShadow.masksToBounds = true
    // Shadow properties
    innerShadow.shadowColor = UIColor.black.cgColor
    innerShadow.shadowOffset = CGSize(width: 0, height: 3)
    innerShadow.shadowOpacity = 0.05
    innerShadow.shadowRadius = 3
    innerShadow.cornerRadius = self.frame.size.height/2
    layer.addSublayer(innerShadow)
}
Run Code Online (Sandbox Code Playgroud)

结果:

在此输入图像描述

更新:

override func layoutSubviews(){super.layoutSubviews()self.layer.cornerRadius = self.frame.size.height/2 self.addInnerShadow()}

private func addInnerShadow() {
    let innerShadow = CALayer()
    innerShadow.frame = bounds
    // Shadow path (1pt ring around bounds)
    let path = UIBezierPath(roundedRect: innerShadow.bounds.insetBy(dx: -1, dy: -1), cornerRadius: self.frame.size.height/2)
    let cutout = UIBezierPath(rect: innerShadow.bounds).reversing()
    path.append(cutout)
    innerShadow.shadowPath = path.cgPath
    innerShadow.masksToBounds = true
    // Shadow properties
    innerShadow.shadowColor = UIColor.black.cgColor
    innerShadow.shadowOffset = CGSize(width: 0, height: 3)
    innerShadow.shadowOpacity = 0.05
    innerShadow.shadowRadius = 3
    //innerShadow.cornerRadius = self.frame.size.height/2
    layer.addSublayer(innerShadow)
}
Run Code Online (Sandbox Code Playgroud)

结果:

在此输入图像描述 角半径导致问题,因为路径仍然是矩形,阴影看起来不同

小智 13

只需使用圆角矩形路径:

private func addInnerShadow() {
    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.black.cgColor
    innerShadow.shadowOffset = CGSize(width: 0, height: 3)
    innerShadow.shadowOpacity = 0.15
    innerShadow.shadowRadius = 3
    innerShadow.cornerRadius = self.frame.size.height/2
    layer.addSublayer(innerShadow)
}
Run Code Online (Sandbox Code Playgroud)

结果截图