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

标签 ios swift3

之前的 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/

相关文章:

ios - 以恒定速度将 imageView 从当前位置移动到点击位置

ios - 正常应用程序启动和 WatchKit 的 sendMessage 唤醒之间的区别?

swift - 从父 View 中删除 View

ios - 单击Xco​​de 4.3.3时,保持按钮突出显示

ios - 单例类加载数据

ios - 如何保存到 Firebase - Swift

ios - Facebook 登录按钮不转到 Safari,而是转到应用程序,然后出现故障

swift3 - swift 3 日期选择器仅显示日月年

file - TVOS FileManager 的 createFile 失败并出现错误 1

ios - 执行 `layoutSubviews` 绘图_without_子类化 View ,而不是使用闭包?