带有圆角的 UITextField 中的内部阴影

Inner shadow in UITextField with rounded corners

我想实现这个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)
}

结果:

更新:

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)
}

结果:

拐角半径导致了问题,因为路径仍然是矩形并且阴影看起来不同

只需使用圆角矩形路径:

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)
}

为此 - 我添加了一个 uiimageview 并将图像输入为阴影文本单元格,然后在具有清晰背景的 uiimageview 顶部放置了一个标签,这样您就可以通过文本看到阴影图像。这一切都是通过故事板完成的,所以我没有代码可以展示,也不允许上传图片。希望这可以帮助。