MdaG
MdaG

Reputation: 2730

How do I add shadows to a view using interface builder?

I've read that @IBInspectable and @IBDesignable are needed for this to be possible and I've made it work for cornerRadius. Alas my attempt doesn't work for shadow parameters. My code below:

@IBDesignable class DesignableView: UIView {}

extension UIView {
  @IBInspectable var shadowRadius: CGFloat {
    get {
      return layer.shadowRadius
    }
    set {
      layer.shadowRadius = newValue
    }
  }
  @IBInspectable var shadowOffset: CGSize {
    get {
      return layer.shadowOffset
    }
    set {
      layer.shadowOffset = newValue
    }
  }
  @IBInspectable var shadowColor: UIColor? {
    get {
      var color: UIColor? = nil
      if let cgColor = layer.shadowColor {
        color = UIColor(cgColor: cgColor)
      }
      return color
    }
    set {
      layer.shadowColor = newValue?.cgColor
    }
  }
  @IBInspectable var cornerRadius: CGFloat { // This works, but not the ones above
    get {
      return layer.cornerRadius
    }
    set {
      layer.cornerRadius = newValue
      layer.masksToBounds = (newValue > 0)
    }
  }
}

I then add a view in interface builder and set is as an DesignableView. After that I can freely alter the cornerRadius and it'll update accordingly, but not the shadow parameters. They're visible in interface builder, but manipulating the values doesn't change the visuals; not even after compile and while running in the application.

What have I missed?

EDIT: I detected the error with the help of the answers to this question. To make it work add shadowOpacity (and set it to 1 in Interface builder)

@IBInspectable var shadowOpacity: Float {
    get {
      return layer.shadowOpacity
    }
    set {
      layer.shadowOpacity = newValue
    }
  }

and remove layer.masksToBounds = (newValue > 0) from cornerRadius.

Upvotes: 0

Views: 1421

Answers (2)

Vaibhav Parmar
Vaibhav Parmar

Reputation: 481

Try this

func decorateView() {
  view.layer.masksToBounds = false
  view.layer.shadowOffset = CGSize(width: 0, height:1)
  view.layer.shadowOpacity = 0.1
  view.layer.shadowRadius = 7
  view.layer.shadowColor = .gray
}

call this function in awakeFromNib()

Upvotes: 0

Pochi
Pochi

Reputation: 13459

You are missing:

yourView.layer.shadowOpacity = 1

Upvotes: 2

Related Questions