在Swift中,可以通过以下步骤将阴影仅添加到UIView的顶部和底部:
let shadowView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 100))
shadowView.backgroundColor = UIColor.white
shadowView.layer.cornerRadius = 10
let shadowLayer = CALayer()
shadowLayer.shadowColor = UIColor.black.cgColor
shadowLayer.shadowOffset = CGSize(width: 0, height: 2)
shadowLayer.shadowOpacity = 0.5
let shadowPath = UIBezierPath()
shadowPath.move(to: CGPoint(x: 0, y: 0))
shadowPath.addLine(to: CGPoint(x: shadowView.bounds.width, y: 0))
shadowPath.move(to: CGPoint(x: 0, y: shadowView.bounds.height))
shadowPath.addLine(to: CGPoint(x: shadowView.bounds.width, y: shadowView.bounds.height))
shadowLayer.shadowPath = shadowPath.cgPath
shadowView.layer.addSublayer(shadowLayer)
完整的代码示例:
import UIKit
let shadowView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 100))
shadowView.backgroundColor = UIColor.white
shadowView.layer.cornerRadius = 10
let shadowLayer = CALayer()
shadowLayer.shadowColor = UIColor.black.cgColor
shadowLayer.shadowOffset = CGSize(width: 0, height: 2)
shadowLayer.shadowOpacity = 0.5
let shadowPath = UIBezierPath()
shadowPath.move(to: CGPoint(x: 0, y: 0))
shadowPath.addLine(to: CGPoint(x: shadowView.bounds.width, y: 0))
shadowPath.move(to: CGPoint(x: 0, y: shadowView.bounds.height))
shadowPath.addLine(to: CGPoint(x: shadowView.bounds.width, y: shadowView.bounds.height))
shadowLayer.shadowPath = shadowPath.cgPath
shadowView.layer.addSublayer(shadowLayer)
这样,你就可以在UIView的顶部和底部添加阴影了。
领取专属 10元无门槛券
手把手带您无忧上云