首页 > 解决方案 > Swift 阴影没有正确传播

问题描述

我一直在尝试为我的 UIView 创建一个阴影。我环顾四周,从这篇文章中找到了 CALayer 类的扩展。https://stackoverflow.com/a/48489506/9188318

到目前为止,它对我来说一直运作良好,直到我尝试为点差输入一个非 0 数字。

点差为 0。这是结果

使用 0 点差

这是使用传播 1 的结果

使用 1 个点差

传播 5 时情况变得更糟

使用 5 的点差

我遇到的问题是它没有圆角,我不知道如何解决这个问题。这是我使用此视图的 UIView 的代码。用于制作阴影的扩展在上面的帖子中。

UIView 代码

class FileCalculateOperatorSelectionButton : UIView {

    private var isActivated : Bool = false

    //Background colors
    private var unSelectedBackgroundColor : UIColor = UIColor(red: 178/255, green: 90/255, blue: 253/255, alpha: 1.0)
    private var selectedBackgroundColor : UIColor = UIColor.white
   
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.commonInit()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        self.commonInit()
    }

    private func commonInit() {
        self.layer.cornerRadius = self.frame.height/2
        self.backgroundColor = self.unSelectedBackgroundColor
    
        let shadowColor = UIColor(red: 0xC8, green: 0xC6, blue: 0xC6)

        //Change the spread argument here
        self.layer.applySketchShadow(color: .black, alpha: 0.5, x: 0, y: 0, blur: 5, spread: 0)
    }   
}

标签: swiftshadowsketchapp

解决方案


尝试将layer's masksToBounds属性设置为true.

self.layer.masksToBounds = true

推荐阅读