阴影层超出了表格视图单元格的边界

问题描述 投票:0回答:1

正在尝试向视图添加阴影。目前我有一个按钮和一个UIView,其中UIView在按钮后面,并且与按钮具有相同的框架。 UIView的约束是button的[顶部,底部,前导,尾随]。

添加阴影的代码如下:

func applySketchShadow(color: UIColor = .black, alpha: Float = 0.5,
    x: CGFloat = 0, y: CGFloat = 2, blur: CGFloat = 4, spread: CGFloat = 0, bgColor: UIColor = .white){

    let shadowLayer = CAShapeLayer()
    shadowLayer.path = UIBezierPath(roundedRect: bounds, cornerRadius: self.bounds.height/2).cgPath
    shadowLayer.fillColor = bgColor.cgColor
    shadowLayer.shadowColor = color.cgColor
    if spread == 0 {
        shadowPath = nil
    } else {
        let dx = -spread
        let rect = bounds.insetBy(dx: dx, dy: dx)
        shadowPath = UIBezierPath(rect: rect).cgPath
    }
    shadowLayer.shadowOffset = CGSize(width: x, height: y)
    shadowLayer.shadowOpacity = alpha
    shadowLayer.shadowRadius = blur / 2.0

    self.insertSublayer(shadowLayer, at: 0)
    self.layoutIfNeeded()
    self.setNeedsLayout()

}

我在具有上述按钮和视图的tableview单元格中调用此代码。我在调用tableview单元格函数的代码如下:

extension GradientButtonCell {

func initCell(topColor : UIColor , bottomColor : UIColor , text : String , orientation : GradientOrientation , textColor : UIColor){

    self.gradientButton.applyGradient(
        withColours: [topColor , bottomColor],
        gradientOrientation: orientation
    )
    self.gradientButton.setTitleColor(textColor, for: .normal)
    self.gradientButton.setTitle(text, for: .normal)
    self.gradientButton.titleLabel?.font = UIFont().nexaBold(withSize: 14.0)
    self.gradientButton.layer.masksToBounds = true
    self.gradientButton.layer.cornerRadius = self.gradientButton.frame.height/2
    self.shadowView.layer.applySketchShadow(
        color: UIColor.hotPink60,
        alpha: 0.6,
        x: 0,
        y: 2,
        blur: 15,
        spread: -20
    )

}

}

但是由于某些原因,阴影层不断超出图像所示的范围。

the white layer is going out of bounds from UIView behind the continue button.

任何有关纠正此问题的想法都值得赞赏。

ios swift uitableview calayer bounds
1个回答
1
投票

添加UIView的此扩展名:

extension UIView {
    func addShadow(
        backgroundColor: UIColor = .white,
        cornerRadius: CGFloat = 5,
        shadowOpacity: Float = 1,
        shadowRadius: CGFloat = 2,
        shadowColor: UIColor = .lightGray,
        shadowOffset: CGSize = CGSize(width: 1, height: 1)
    ) {
        self.backgroundColor = backgroundColor
        self.layer.masksToBounds = false
        self.layer.cornerRadius = cornerRadius
        self.layer.shadowOpacity = shadowOpacity
        self.layer.shadowRadius = shadowRadius
        self.layer.shadowColor = shadowColor.cgColor
        self.layer.shadowOffset = shadowOffset
    }
}

然后尝试调用这样的名称

self.shadowView.addShadow(
    backgroundColor: .blue,
    cornerRadius: 10,
    shadowOpacity: 0.7,
    shadowRadius: 5,
    shadowColor: .lightGray,
    shadowOffset: .zero
)
© www.soinside.com 2019 - 2024. All rights reserved.