Alwin Vazhappilly
Alwin Vazhappilly

Reputation: 1514

How to give bottom shadow to UIView in Swift 3?

enter image description here

This I want

enter image description here

My Code

let shadowPath = UIBezierPath(rect: shadowView.bounds).cgPath
shadowView.layer.shadowColor = UIColor.grey.cgColor
shadowView.layer.shadowOffset = CGSize(width: 0, height: 1)
shadowView.layer.shadowOpacity = 0.5
shadowView.layer.masksToBounds = false
shadowView.layer.shadowPath = shadowPath
shadowView.layer.shadowRadius = 5

I want to implement exactly same shadow in my UIVIew. When I run my app with above code it spread over 4 sides. Notice : the shadow thin at both edges and bold at centre.

Upvotes: 4

Views: 15028

Answers (3)

Chris Prince
Chris Prince

Reputation: 7564

Slight change to @jonaszmclaren to give a rectangular shadow:

func makeBottomShadow(forView view: UIView, shadowHeight: CGFloat = 5) {
    let shadowPath = UIBezierPath()
    shadowPath.move(to: CGPoint(x: 0, y: view.bounds.height))
    shadowPath.addLine(to: CGPoint(x: view.bounds.width, y: view.bounds.height))
    shadowPath.addLine(to: CGPoint(x: view.bounds.width, y: view.bounds.height + shadowHeight))
    shadowPath.addLine(to: CGPoint(x: 0, y: view.bounds.height + shadowHeight))
    shadowPath.close()

    view.layer.shadowColor = UIColor.darkGray.cgColor
    view.layer.shadowOpacity = 0.5
    view.layer.masksToBounds = false
    view.layer.shadowPath = shadowPath.cgPath
    view.layer.shadowRadius = 2
}

Upvotes: 3

jonaszmclaren
jonaszmclaren

Reputation: 2489

Try creating custom path:

let shadowPath = UIBezierPath()
shadowPath.move(to: CGPoint(x: someView.bounds.origin.x, y: someView.frame.size.height))
shadowPath.addLine(to: CGPoint(x: someView.bounds.width / 2, y: someView.bounds.height + 7.0))
shadowPath.addLine(to: CGPoint(x: someView.bounds.width, y: someView.bounds.height))
shadowPath.close()

shadowView.layer.shadowColor = UIColor.darkGray.cgColor
shadowView.layer.shadowOpacity = 1
shadowView.layer.masksToBounds = false
shadowView.layer.shadowPath = shadowPath.cgPath
shadowView.layer.shadowRadius = 5

This gives similiar results, try to customize points positions and other values to match your needs.

Upvotes: 12

arpita
arpita

Reputation: 175

Try This out

IBOutlet

@IBOutlet weak var vwShadow: UIView!

In ViewdidLoad

vwShadow.layer.shadowColor = UIColor.gray.cgColor
vwShadow.layer.masksToBounds = false
vwShadow.layer.shadowOffset = CGSize(width: 0.0 , height: 5.0)
vwShadow.layer.shadowOpacity = 1.0
vwShadow.layer.shadowRadius = 1.0

Upvotes: 2

Related Questions