首页 > 解决方案 > 在 Objective C 中看不到 Swift 变量/方法

问题描述

我无法从Objective C中看到要设置的方法/变量,myVar即使true我已经添加了@objcandpublic修饰符并且方法签名Bool中没有。setMyVarTrue()

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

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

如何Bool从 Objective C 设置 Swift?

SWIFT代码:

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

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

目标C代码:

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

标签: iosobjective-cswiftbridging-headerobjective-c-swift-bridge

解决方案


你应该做

  1. 将@objc 添加到您的班级声明中

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

  3. 在要调用的目标 C 文件中导入“yourName-swift.h”

你的快速课程


推荐阅读