uiview下没有阴影

时间:2017-08-14 14:06:41

标签: ios

您好我想在UITextField下获得一个阴影。我已经对UIView进行了以下扩展。但如果切断了TextField的一半ui。

如何在UIView / UITextField下面添加阴影?

public extension UIView {
    func installShadow() {
        self.layer.masksToBounds = false
        self.layer.backgroundColor = UIColor.white.cgColor
        self.layer.shadowColor = UIColor.lightGray.cgColor
        self.layer.shadowRadius = 5
        self.layer.shadowOpacity = 1
        self.layer.shadowOffset = CGSize(width: 0, height: 1)

        let shadowPath = CGPath(ellipseIn: CGRect(x: self.frame.origin.x,
                                                  y: self.frame.origin.y,
                                                  width: self.frame.size.width,
                                                  height: self.frame.size.height),
                                transform: nil)

        self.layer.shadowPath = shadowPath
    }
}

2 个答案:

答案 0 :(得分:0)

您主要有2个问题, 1。使用框架代替Bounds, 2。使用CGPath(ellipseIn:您的路径将是一个椭圆

使用此代码

public extension UIView {
    func installShadow() {
        self.layer.masksToBounds = false
        self.layer.backgroundColor = UIColor.white.cgColor
        self.layer.shadowColor = UIColor.lightGray.cgColor
        self.layer.shadowRadius = 5
        self.layer.shadowOpacity = 1
        self.layer.shadowOffset = CGSize(width: 0, height: 1)
        self.layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
    }
}

希望这有助于你

答案 1 :(得分:0)

Try these ...

public extension UIView {
    func installShadow() {
let shadowSize : CGFloat = 0.5
layer.clipsToBounds = true
            let shadowPath = UIBezierPath(rect: CGRect(x: -shadowSize / 2,
                                                       y: -shadowSize / 2,
                                                       width: subView!.frame.size.width + shadowSize,
                                                       height: subView!.frame.size.height + shadowSize))
            self.layer.masksToBounds = false
            self.layer.shadowColor = UIColor.darkGray.cgColor
            self.layer.shadowOffset = CGSize(width: 0, height: 0)
            self.layer.shadowOpacity = 0.2
            self.layer.shadowRadius = 5.0
            self.layer.cornerRadius = 5.0
            self.layer.shadowPath = shadowPath.cgPath
}
}