ios - 从 Objective-C 文件调用 UIImageView 的 Swift 扩展中的方法

标签 ios objective-c swift extension-methods

我可以从 Objective-C 文件调用 Swift 文件中的 UIImage 扩展。

但由于某些原因,我无法在 UIImageView 的扩展上调用以下方法。 UIImageView 是否有问题,是我的语法不对还是哪里出了问题?

extension UIImageView {
    /// Retrieve the scaled size of the image within this ImageView.
    /// - Returns: A CGRect representing the size of the image after scaling or nil if no image is set.
    func getScaledImageSize() -> CGRect? {
        if let image = self.image {
            return AVMakeRect(aspectRatio: image.size, insideRect: self.frame);
        }

        return nil;
    }
}

Objective-C 文件中的代码:

 CGRect myRect = [self.imageView getScaledImageSize];

给出“UIImageView 没有可见界面声明选择器 getScaledImageSize”错误

最佳答案

您至少需要解决三件事。

在您的 Objective-C 文件中,您需要添加以下 import 语句:

#import "ProductModuleName-Swift.h"

其中“ProductModuleName”是您的项目名称。

您需要将@objc 属性添加到您的扩展类:

@objc extension UIImageView

您需要更改方法以返回非可选值。这是一个建议的实现:

func getScaledImageSize() -> CGRect {
    if let image = self.image {
        return AVMakeRect(aspectRatio: image.size, insideRect: self.frame)
    }

    return CGRect.zero
}

关于ios - 从 Objective-C 文件调用 UIImageView 的 Swift 扩展中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53604812/

相关文章:

ios - iOS NSURLSession 是否支持 HTTP 100-continue?

ios - setZoomScale 不适用于 UIWebView

ios - Core Graphics 和 Open GL 绘图

iphone - 插入时间范围 :ofTracks:atTime:error:

ios - iPhone-如何在圆形按钮的 ImageView 中设置纵向/横向图像

ios - 从配置文件 iOS 获取详细信息

ios - NSFetchedResultsController 发现错误数量的对象

ios - UINavigationBar 底部边框消失

ios - 无法将类型 'Swift._ContiguousArrayStorage<AppName.JobsNearBy>' (0x113b1a200) 的值转换为 'AppName.JobsNearBy' (0x10e6e7e60)

Swift3 为可为空的对象赋值