css - 如何将 css 盒子阴影转换为 IOS 阴影
问题描述
我想知道如何将以下 CSS 框阴影转换为 iOS 阴影。CSS框阴影如下
box-shadow: -2px -4px 4px 0 #e5e5e5, 2px 4px 4px 0 rgba(0, 0, 0, 0.25);
解决方案
如果这是你想要的:
您可以通过设置视图的layer
阴影并添加带有另一个阴影的子层来做到这一点:
class BoxShadowView: UIView {
let layer1 = CALayer()
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
func commonInit() -> Void {
layer.masksToBounds = false
layer.shouldRasterize = true
layer.shadowRadius = 4
layer.shadowOffset = CGSize(width: -2, height: -4)
layer.shadowColor = UIColor.black.cgColor
layer.shadowOpacity = 0.1
layer1.masksToBounds = false
layer1.shouldRasterize = true
layer1.shadowRadius = 4
layer1.shadowOffset = CGSize(width: 2, height: 4)
layer1.shadowColor = UIColor.black.cgColor
layer1.shadowOpacity = 0.25
layer.addSublayer(layer1)
}
override func layoutSubviews() {
super.layoutSubviews()
layer1.backgroundColor = backgroundColor?.cgColor
layer1.frame = bounds
}
}
这是一个简单的示例用法(我用来创建该图像的内容):
class BoxShadowTestViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// create a BoxShadowView
let boxView = BoxShadowView()
// create a label
let label = UILabel()
[boxView, label].forEach {
$0.translatesAutoresizingMaskIntoConstraints = false
}
// add label to boxView
boxView.addSubview(label)
// add boxView to view
view.addSubview(boxView)
// respect safe area
let g = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
// boxView Width & Height
boxView.widthAnchor.constraint(equalToConstant: 240.0),
boxView.heightAnchor.constraint(equalToConstant: 120.0),
// center in view
boxView.centerXAnchor.constraint(equalTo: g.centerXAnchor),
boxView.centerYAnchor.constraint(equalTo: g.centerYAnchor),
// center label in boxView
label.centerXAnchor.constraint(equalTo: boxView.centerXAnchor),
label.centerYAnchor.constraint(equalTo: boxView.centerYAnchor),
])
// set boxView background color
boxView.backgroundColor = .white
// set label text
label.text = "Test Label"
}
}
推荐阅读
- c++ - 从文件中读取多个字节并存储它们以在 C++ 中进行比较
- ionic-framework - 我在 ionic 的应用浏览器中使用。它在移动浏览器而不是应用程序上打开 url
- python - pycharm 项目:源根目录和导入未更新?
- c# - 将 EF Core 3.1 转换为存储字符串枚举值,而不是整数
- android - FirebaseUI-Android - oAuth 登录后自定义 Chrome 选项卡不会自动关闭(Microsoft 和 Apple)
- database - MongoDB 分片,MongoDB 路由器的“mongos”是否存在瓶颈?
- stata - 循环遍历全局宏
- java - 如何在查询 addchildeventlistner 中检查 recyclerview 是否为空
- reactjs - 我正在尝试从给定索引处的数组中访问一个值,但我一直未定义
- python - Python 本身是否使用 Hashable 类打破了继承基础?