Swift 中的 UIView 扩展

UIView extension in Swift

我在 swift.
编写的实用程序 class 中放置了一个 UIView extension 但是,当我尝试从扩展中调用方法时,

编译器告诉我

The member does not exist

这是我的分机:

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
    }
}

自从 UIImage subclasses UIView,我想我应该能够将该方法应用于 UIViewController 中的自定义 MKAnnotation 图像通过调用

myImage.addShadow()

但是,我收到错误消息:

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

如果我将方法放在 UIImage 的扩展中,我会得到同样的错误。

我是否必须以某种方式告诉 UIViewController 有关实用程序 class 的信息,或者我的代码可能有什么问题?

您正在为 UIView 延期。不是 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
    }
}

另外请直接使用UIImageVIew,不要使用UIImage

编辑

根据您的评论,我认为您正在尝试修改 MKAnnotationView。如果是这样,这里的问题会对您有所帮助。

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