ios - 为什么我的阴影层位置不正确?

标签 ios swift scrollview shadow

我有一个名为 RoundedViewUIView 自定义子类:

import UIKit

@IBDesignable
class RoundedView: UIView {

    @IBInspectable var shadowColor : UIColor? {
        didSet {
            layer.shadowColor = shadowColor?.cgColor
            layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
        }
    }

    @IBInspectable var shadowOffset : CGSize = CGSize(width: 20, height: 20) {
        didSet {
            layer.shadowOffset = shadowOffset
            layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
        }
    }

    @IBInspectable var shadowRadius : CGFloat = 0.0 {
        didSet {
            layer.shadowRadius = shadowRadius
            layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
        }
    }

    @IBInspectable var shadowOpacity : Float = 1.0 {
        didSet {
            layer.shadowOpacity = shadowOpacity
            layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
        }
    }


}

通过这个类,我希望能够使用 Xcode Interface Builder 设置 View 的阴影。 不幸的是,这种行为很奇怪。当设置颜色为蓝色、偏移量为CGSize.zero、半径为0、不透明度为1时,整个阴影向右移动:

这是 1. 阴影路径、2. 边界和 3. 框架的输出:

shadowPath: 
    Path 0x60800022e040:
      moveto (0, 0)
        lineto (300, 0)
        lineto (300, 150)
        lineto (0, 150)
        closepath
self.bounds: 
    (0.0, 0.0, 300.0, 150.0)
self.frame: 
    (37.0, 268.5, 300.0, 150.0)

我不知道为什么会发生这种情况。你能帮我一下吗?

最佳答案

我不能简单地写下这一行

layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath

进入每个 didSet 观察者,因为框架可能仍然会改变。

通过重写函数 layoutSubviews 并在其中添加行来解决。

关于ios - 为什么我的阴影层位置不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50046010/

相关文章:

ios - 在仪器中前台运行

android - ScrollView 没有重力。如何使 ScrollView 内的内容为中心

ios - 为非 gailbreak 设备中已安装的应用下载和安装 .IPA 文件(开发应用商店)

iphone - Facebook SDK : How to i get the photo properties after posting an image?

ios - 如何创建三态开关按钮?

ios - 在没有动画的情况下关闭 View Controller 后立即显示 View Controller

android - RelativeLayout 中的 ScrollView

java - 膨胀 View 并调用scrollBy时 ScrollView 闪烁

ios - 当有多个 APN 堆叠时,如何获取 APN 的有效负载?

ios - 如何让stackview在向下滚动时消失,向上滚动时重新出现?