2017-08-14 105 views
0

嗨我想在UITextField下得到阴影。我已经对UIView进行了如下扩展。但是,如果切断TextField的一半用户界面。uiview下没有阴影

如何在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 
    } 
} 
+0

您正在使用'CGPath(ellipseIn:'这是故意的吗? –

+0

试试这个'self.layer.shadowPath = UIBezierPath(rect:self.bounds).cgPath' –

+0

你需要显示一个图像,你希望看到结果。 – DonMag

回答

0

你有2个问题主要是,使用框架,而不是边界,并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 
    } 
} 

希望这对你有所帮助

+0

@ChrisG你可以upvote我的答案? –

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 
} 
}