Trevor
Trevor

Reputation: 2457

iOS shadow view in interface builder

I'm trying to add shadows to some views via interface builder. I can't seem to get shadows to work on my views. All the resources I look at point to this same code so I'm not sure what I'm doing wrong.

Interface Builder

Interface Builder

Interface Builder Extension code

import Foundation
import UIKit

extension UIView {

    //cut irrelevant code for SO Question

    @IBInspectable
    var masksToBounds: Bool {
        get {
            return layer.masksToBounds
        }
        set {
            layer.masksToBounds = newValue
        }
    }


    // Shadow handling
    @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
            }
        }
    }

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


    @IBInspectable
    var shadowRadius: CGFloat {
        get {
            return layer.shadowRadius
        }
        set {
            layer.shadowRadius = newValue
        }
    }

    @IBInspectable
    var shadowOffset: CGSize {
        get {
            return layer.shadowOffset
        }
        set {
            layer.shadowOffset = newValue
        }
    }


}

Views layout

enter image description here

This is the result

enter image description here

Upvotes: 2

Views: 1019

Answers (2)

TylerP
TylerP

Reputation: 9829

Your shadowOpacity property is accessing the wrong layer property. It's accessing layer.opacity when it should be layer.shadowOpacity. Also, your shadowRadius is way too large and should probably be around 5 (depending on what you're going for, of course), not 500.

Upvotes: 2

Amber K
Amber K

Reputation: 698

I guess it's your custom search bar to which you're adding shadow. The reason its not visible I guess is because your both view in controller and storyboard of same size. Try to make the storyboard view have a container view in it with some padding along to the storyboard view and add that shadow to that container view. This might show some results.

Upvotes: 1

Related Questions