gpt4 book ai didi

ios - 使用 swift 3 在 UIView 上添加阴影

转载 作者:IT王子 更新时间:2023-10-29 07:35:35 24 4
gpt4 key购买 nike

之前的 swift 3 我是这样在我的 UIView 中添加阴影的:

//toolbar is an UIToolbar (UIView)
toolbar.layer.masksToBounds = false
toolbar.layer.shadowOffset = CGSize(width: -1, height: 1)
toolbar.layer.shadowRadius = 1
toolbar.layer.shadowOpacity = 0.5

但是上面的代码在 swift 3 中不起作用,我的整个 View 的颜色没有阴影而是变成了难看的灰色

有人知道我们如何在 swift 3 中添加阴影吗?

最佳答案

代码片段:

extension UIView {

// OUTPUT 1
func dropShadow(scale: Bool = true) {
layer.masksToBounds = false
layer.shadowColor = UIColor.black.cgColor
layer.shadowOpacity = 0.5
layer.shadowOffset = CGSize(width: -1, height: 1)
layer.shadowRadius = 1

layer.shadowPath = UIBezierPath(rect: bounds).cgPath
layer.shouldRasterize = true
layer.rasterizationScale = scale ? UIScreen.main.scale : 1
}

// OUTPUT 2
func dropShadow(color: UIColor, opacity: Float = 0.5, offSet: CGSize, radius: CGFloat = 1, scale: Bool = true) {
layer.masksToBounds = false
layer.shadowColor = color.cgColor
layer.shadowOpacity = opacity
layer.shadowOffset = offSet
layer.shadowRadius = radius

layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
layer.shouldRasterize = true
layer.rasterizationScale = scale ? UIScreen.main.scale : 1
}
}

NOTE: If you don't pass any parameter to that function, then the scale argument will be true by default. You can define a default value for any parameter in a function by assigning a value to the parameter after that parameter’s type. If a default value is defined, you can omit that parameter when calling the function.

输出 1:

shadowView.dropShadow()

enter image description here

输出 2:

shadowView.dropShadow(color: .red, opacity: 1, offSet: CGSize(width: -1, height: 1), radius: 3, scale: true)

enter image description here

layer.shouldRasterize = true will make the shadow static and cause a shadow for the initial state of the UIView. So I would recommend not to use layer.shouldRasterize = true in dynamic layouts like view inside a UITableViewCell.

关于ios - 使用 swift 3 在 UIView 上添加阴影,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39624675/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com