【问题标题】:Why is my shadow layer not positioned correctly?为什么我的阴影层没有正确定位?
【发布时间】:2018-04-26 14:47:39
【问题描述】:

我有一个 UIView 的自定义子类,称为 RoundedView

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 为视图设置阴影。 不幸的是,这种行为很奇怪。当设置颜色为蓝色,偏移量为CGSize.zero,半径为0,不透明度为1时,整个阴影向右移动:

这是 1.shadowPath、2.bounds 和 3.frame 的输出:

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)

我不知道为什么会这样。你能帮帮我吗?

【问题讨论】:

  • 尝试将clipToBounds设置为true。
  • @iOSDeveloper 这没有帮助,如果我设置clipToBounds,阴影会被隐藏。此外,它可以与其他视图一起使用,而无需将 clipsToBounds 设置为 true。
  • layer.shadowRadius 设置一些值。它不能为零。
  • @SeyedSamadGholamzadeh 我试过了,没有结果。我认为它可以为零,它适用于正常视图。
  • 哦,你使用了shadowPath。我认为这就是重点。因为当您滚动视图位置时会发生变化,但 shadowPath 是不变的。尝试在您编写的layer.shadowPath 之后添加layer.shouldRasterize = true 并检查这是否解决了您的问题?

标签: ios swift scrollview shadow


【解决方案1】:

我不能简单地说这行

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

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

通过覆盖函数layoutSubviews 并在此处添加该行来解决。

【讨论】:

    猜你喜欢
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多