Search code examples
iosswiftuiimageswift-extensions

UIView extension in Swift


I have placed a UIView extension in a utilities class written in swift.
However, when I try to call a method from the extension,

The compiler tells me the

The member does not exist

Here is my extension:

extension UIView {
    func addShadow() {
        layer.shadowColor = UIColor.black.cgColor
        layer.shadowOffset = CGSize(width: 0, height: 0)
        layer.shadowOpacity = 0.5
        layer.shadowRadius = 5
        clipsToBounds = false
    }
}

Since UIImage subclasses UIView, I think I should be able to apply the method to a custom MKAnnotation image in a UIViewController by calling

myImage.addShadow()

However, I get error:

Value of type 'UIImage' has no member 'addShadow'

If I place the method in an extension of UIImage, I get same error.

Do I have to tell the UIViewController about the utilities class somehow or what could be wrong with my code?


Solution

  • You're making an extension for UIView. Not UIImageView

    extension UIImageView {
    
        func addShadow() {
            layer.shadowColor = UIColor.black.cgColor
            layer.shadowOffset = CGSize(width: 0, height: 0)
            layer.shadowOpacity = 0.5
            layer.shadowRadius = 5
            clipsToBounds = false
        }
    }
    

    Also please use the UIImageVIew directly, not the UIImage

    EDIT

    Assuming by your comments, i think you're trying to modify an MKAnnotationView. If so here's a question that will help you.

    How to create rounded image with border and shadow as MKAnnotationView in Swift?