无法在iOS中设置UIView的底部阴影?

时间:2017-05-02 09:04:51

标签: ios swift xcode uiview

我想设置UIView的底部阴影。我也设置角半径。如果我将 maskToBounds 设置为 true ,那么我无法设置阴影UIView请告诉我如何设置角半径和? UIView的影子。

 func addShadwToView(){
    self.viewContainer.layer.masksToBounds = true;
    self.viewContainer.layer.shadowRadius = 15;
    self.viewContainer.layer.shadowOffset = CGSize(width: 0, height: 20)
    self.viewContainer.layer.shadowOpacity = 0.5;
    self.viewContainer.layer.cornerRadius = 5
    self.viewContainer.layer.borderColor = UIColor.lightGray.cgColor
    self.viewContainer.layer.borderWidth = 0.5
  }

2 个答案:

答案 0 :(得分:0)

如果你想要一个角半径和一个阴影,那么不要打开-masksToBounds,而是设置角半径并用圆角矩形设置阴影的bezier路径。保持两者的半径相同: 试试吧:

func addShadwToView(){
                    var borderLine = CAShapeLayer()
                    borderLine.path =  UIBezierPath(roundedRect: frame2, byRoundingCorners: [.allCorners], cornerRadii: CGSize(width: 30, height: 0)).cgPath
                    borderLine.shadowColor = UIColor.white.cgColor
                    borderLine.shadowOffset = CGSize(width: 0, height: 1)
                    borderLine.shadowOpacity = 0.3
                    borderLine.shadowRadius = 10

                    self.viewContainer.layer.masksToBounds = true;
                    self.viewContainer.layer.cornerRadius = 5
                    self.viewContainer.layer.borderColor = UIColor.lightGray.cgColor
                    self.viewContainer.layer.borderWidth = 0.5
                    self.viewContainer.layer.addSublayer(borderLine)
                }

答案 1 :(得分:0)

尝试此代码......这将解决您的问题

    func addShadow(){
        let shadowPath = UIBezierPath(rect: CGRect(x: 0, y: 0, width: customView.frame.width, height: customView.frame.height))
        customView.layer.shadowColor = UIColor.lightGray.cgColor
        customView.layer.shadowOffset = CGSize(width: 0, height: 20)
        customView.layer.shadowOpacity = 0.5
        customView.layer.shadowRadius = 15
        customView.layer.masksToBounds =  false
        customView.layer.shadowPath = shadowPath.cgPath
}