在 Objective C 中看不到 Swift variable/method

Can't see Swift variable/method in Objective C

我无法看到 method/variable 从 Objective C 将 myVar 设置为 true 即使困难我已经添加了 @objcpublic 修饰符并且 setMyVarTrue() 方法的签名中没有 Bool

这可能是由于Swift的Bool和Objective C的BOOL不同造成的。

其他 class methods/variables 可见,只有这个不可见。

如何从 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 添加到您的 class

  2. 声明中
  3. 添加一个名为 "yourName-swift.h" 的文件,该文件应包含 @class yourClass;

  4. import "yourName-swift.h" in Objective C file, where you want to call

你的swiftclass

解决方案是清理并重建项目。 Xcode 自动生成 swift 桥接 header,在我的例子中,它在重新生成桥接 header.

SWIFT_CLASS("_TtC11MyProject25MyViewController")
@interface MyViewController : UIViewController
@property (nonatomic, strong) MBProgressHUD * _Nonnull progressIndicator;
- (nonnull instancetype)initWithNibName:(NSString * _Nullable)nibNameOrNil bundle:(NSBundle * _Nullable)nibBundleOrNil OBJC_DESIGNATED_INITIALIZER;
- (nullable instancetype)initWithCoder:(NSCoder * _Nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER;
- (void)viewDidLoad;
- (void)viewWillAppear:(BOOL)animated;
- (void)submitProgressHandler:(NSNotification * _Nonnull)notification;
- (void)submitSuccessHandler;
- (void)submitFailureHandler:(NSNotification * _Nonnull)notification;
- (void)subscribe;
- (void)unsubscribe;
@end

现在可以正常工作了:

SWIFT_CLASS("_TtC11MyProject25MyViewController")
@interface MyViewController : UIViewController
@property (nonatomic, strong) MBProgressHUD * _Nonnull progressIndicator;
@property (nonatomic) BOOL closing;
- (nonnull instancetype)initWithNibName:(NSString * _Nullable)nibNameOrNil bundle:(NSBundle * _Nullable)nibBundleOrNil OBJC_DESIGNATED_INITIALIZER;
- (nullable instancetype)initWithCoder:(NSCoder * _Nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER;
- (void)viewDidLoad;
- (void)viewWillAppear:(BOOL)animated;
- (void)setClosingTrue;
- (void)submitProgressHandler:(NSNotification * _Nonnull)notification;
- (void)submitSuccessHandler;
- (void)submitFailureHandler:(NSNotification * _Nonnull)notification;
- (void)subscribe;
- (void)unsubscribe;
@end