ios - 在 Objective C 中看不到 Swift 变量/方法

标签 ios objective-c swift bridging-header objective-c-swift-bridge

即使我添加了 @objc,我也无法从 Objective C 中看到将 myVar 设置为 true 的方法/变量和 public 修饰符,并且 setMyVarTrue() 方法的签名中没有 Bool

这可能是由于 Swift 的 Bool 和 Objective C 的 BOOL 之间的差异造成的。

其他类方法/变量是可见的,只有这个特定的方法/变量不可见。

如何从 Objective C 设置 Swift 的 Bool

Swift 代码:

public class MyViewController : UIViewController {
    public var myVar:Bool = false

    @objc public func setMyVarTrue() {
        self.myVar = true
    }
}

objective-c 代码:

MyViewController* myViewController = [MyViewController new];
myViewController.myVar = true // Variable not found
myViewController.setMyVarTrue() // Method not found
[self presentViewController:myViewController animated:NO completion:nil];

最佳答案

你应该这样做

  1. 将 @objc 添加到类的声明中

  2. 添加一个名为“yourName-swift.h”的文件,其中应包含@class yourClass;

  3. 在 Objective C 文件中导入“yourName-swift.h”,您要在其中调用

你的 Swift 类(class)

关于ios - 在 Objective C 中看不到 Swift 变量/方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52273950/

相关文章:

ios - 如何将对连接到数组以包含相同的索引?

cocoa - 在 iOS 4.x 和 MacOS X 10.6 : impossible? 中使用 NSDateFormatter 解析 rfc3339 日期

ios - AVCaptureSession commitConfiguration() 耗时太长

ios - 更改屏幕尺寸 ios 时 View 出现故障

ios - URL 超时的数据任务

ios - 如何快速更新实例变量?

iOS 核心数据 executeFetchRequest 返回空对象

objective-c - NSPredicate 中的减法

iphone - 完成按钮仅适用于数字键盘

iOS:如何检测 UIApplicationDelegate 状态何时变为 "suspended"?