首页 > 解决方案 > 如何在 UIView 顶部设置阴影?

问题描述

class AccountListViewController: UIViewController {       

    @IBOutlet weak var actionButtonView: UIView!

    override func viewDidLoad() {            
       super.viewDidLoad()
       actionButtonView.layer.cornerRadius = 10
       actionButtonView.layer.shadowColor = UIColor.gray.cgColor
       actionButtonView.layer.shadowOffset = .zero
       actionButtonView.layer.shadowOpacity = 0.6
       actionButtonView.layer.shadowRadius = 10
    }

我试过这个但没有得到结果

标签: iosswift

解决方案


您的代码很好,但您需要为阴影偏移指定负值而不是.zero

class AccountListViewController: UIViewController {

    @IBOutlet weak var actionButtonView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        actionButtonView.layer.cornerRadius = 10
        actionButtonView.layer.shadowColor = UIColor.gray.cgColor
        actionButtonView.layer.shadowOffset = CGSize(width: 0.0, height : -5.0)
        actionButtonView.layer.shadowOpacity = 0.6
        actionButtonView.layer.shadowRadius = 10
    }
}

为了更方便,您可以为此创建一个扩展。

请参考以下代码

extension UIView {
    func addTopShadow(shadowColor : UIColor, shadowOpacity : Float,shadowRadius : Float,offset:CGSize){
        self.layer.shadowColor = shadowColor.cgColor
        selflayer.shadowOffset = offset
        self.layer.shadowOpacity = shadowOpacity
        self.layer.shadowRadius = shadowRadius
        self.clipsToBounds = false
    }
}

如何使用?

viewName.addTopShadow(shadowColor: UIColor.gray, shadowOpacity: 0.9, shadowRadius: 10, offset: CGSize(width: 0.0, height : -5.0))

推荐阅读