首页 > 解决方案 > Swift UI 和阴影颜色

问题描述

所以,我需要一个在 iOS / swift 中的按钮,它在底部和右边框上有外阴影,在顶部和左边框上有内阴影。我研究了几天的教程,并想出了以下解决方案,这几乎是我需要的。

internal func Setup() {
        self.backgroundColor = .white

        self.contentEdgeInsets = UIEdgeInsets(top: 10, left:30, bottom: 10,  right: 30)

        // Outer shadow 
        self.layer.shadowColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1).cgColor
        self.layer.shadowOffset = CGSize(width: 10, height: 10)
        self.layer.shadowOpacity = 1.0
        self.layer.shadowRadius = 6
        self.layer.masksToBounds = false
        self.layer.cornerRadius = self.frame.height / 2

        // call to add inner shadow
        self.addInnerShadow()

    }

    internal func addInnerShadow() {
        let cornerRadius = self.bounds.height / 2

        let innerShadow = CALayer()
        innerShadow.frame = bounds
        // Shadow path (1pt ring around bounds)
        let path = UIBezierPath(roundedRect: innerShadow.bounds.insetBy(dx: -1, dy: -1), cornerRadius: cornerRadius)
        let cutout = UIBezierPath(roundedRect: innerShadow.bounds, cornerRadius: cornerRadius).reversing()
        path.append(cutout)

        innerShadow.shadowPath = path.cgPath
        innerShadow.masksToBounds = true

        // Shadow properties. Color is SAME as in outer shadow, but will come out differently
        innerShadow.shadowColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1).cgColor
        innerShadow.shadowOffset = CGSize(width: 8, height: 8)
        innerShadow.shadowOpacity = 1.0
        innerShadow.shadowRadius = 6
        innerShadow.cornerRadius = cornerRadius


        // Add
        layer.addSublayer(innerShadow)
    }

在按钮的 init() 期间调用函数 Setup(),它都创建了带有圆角的漂亮阴影按钮。

在此处输入图像描述

但问题是——为什么顶部的内阴影这么亮?它应该与底部外阴影的颜色相同。如果我设置任何其他颜色(如红色),它总是很浅,只有所需颜色的色调。为什么?是否可以像使用外阴影一样直接控制内阴影的颜色?

标签: iosswiftuser-interface

解决方案


推荐阅读