How do I draw a shadow under a UIView in iPhone/iOS?

iOSMobile DevelopmentiPhone/iPad

To make our UI appealing, we have to play around with multiple attributes in iOS development. To draw shadows around a View or below a view we have to play around Layers and Views.

Let’s see this in two ways.

Method 1 − Simply coding where ever required.

self.layer.masksToBounds = NO;
self.layer.cornerRadius = 2;
self.layer.shadowOffset = CGSizeMake(-5, 10);
self.layer.shadowRadius = 3;
self.layer.shadowOpacity = 0.3;

Method 2 − Creating IBDesignable and IBInspectable and Using with Story board.

@IBDesignable
class DesignableView: UIView { }
extension UIView {
   @IBInspectable
   var shadowRadius: CGFloat {
      get {
         return layer.shadowRadius
      }
      set {
         layer.shadowRadius = newValue
      }
   }
   @IBInspectable
   var shadowOpacity: Float {
      get {
         return layer.shadowOpacity
      }
      set {
         layer.shadowOpacity = newValue
      }
   }
   @IBInspectable
   var shadowOffset: CGSize {
      get {
         return layer.shadowOffset
      }
      set {
         layer.shadowOffset = newValue
      }
   }
   @IBInspectable
   var shadowColor: UIColor? {
      get {
         if let color = layer.shadowColor {
            return UIColor(cgColor: color)
         }
         return nil
      }
      set {
         if let color = newValue {
            layer.shadowColor = color.cgColor
         } else {
            layer.shadowColor = nil
         }
      }
   }
}

Using the above extension for UIView we can make these properties accessible to all the Storyboards and play around with designs without having to run and see the results on device. These changes will be made live on the storyboard. Below is an example of the same.

raja
Published on 28-Dec-2018 12:13:12
Advertisements