在Swift中公开目标C类扩展属性

时间:2023-01-15 14:58:43

Say I have the following in an Objective C implementation file (MyVC.m):

假设在目标C实现文件(MyVC.m)中有以下内容:

@interface MyVC ()
  @property (nonatomic, weak) IBOutlet UILabel *titlelabel;
@end

How can I expose this private property to Swift (test) code? The following causes compiler errors:

如何将此私有属性公开给Swift(测试)代码?造成编译错误的原因如下:

extension LTConversationSelectionVC {
   @IBOutlet weak var assetBar: LTAssetBar?
}

3 个解决方案

#1


1  

From apple doc

从苹果医生


Extensions can add new computed properties, but they cannot add stored properties, or add property observers to existing properties.

扩展可以添加新的计算属性,但不能添加存储属性,也不能向现有属性添加属性观察者。


Apple documentation Link here

苹果的文档链接在这里

#2


1  

Unfortunately, there isn't a way to do this purely with Swift. However, you can expose the property in an Objective-C file in your test target and then put that in your test target's bridging header.

不幸的是,只有斯威夫特没有办法做到这一点。但是,您可以在测试目标中的Objective-C文件中公开该属性,然后将其放在测试目标的桥接头中。

Add MyVC+Tests.h to your test target:

添加MyVC +测试。h到你的测试目标:

@interface MyVC (Tests)
  @property (nonatomic, weak) IBOutlet UILabel *titlelabel;
@end

MyAppTests-Bridging-Header.h

MyAppTests-Bridging-Header.h

#import "MyVC+Tests.h"

Then, in your Swift code in the test target, you can use the titleLabel property as expected.

然后,在测试目标的Swift代码中,可以按照预期使用titleLabel属性。

let vc = MyVC()
vc.titleLabel.text = "Hello, world!"

#3


0  

You can do the same property-in-category trick from the Bridging Header file. Just forward any class that calls swift library. That should take care of the problem.

您可以从桥接头文件中执行相同的属性-in-category技巧。只要转发任何调用swift库的类。那应该能解决这个问题。

#1


1  

From apple doc

从苹果医生


Extensions can add new computed properties, but they cannot add stored properties, or add property observers to existing properties.

扩展可以添加新的计算属性,但不能添加存储属性,也不能向现有属性添加属性观察者。


Apple documentation Link here

苹果的文档链接在这里

#2


1  

Unfortunately, there isn't a way to do this purely with Swift. However, you can expose the property in an Objective-C file in your test target and then put that in your test target's bridging header.

不幸的是,只有斯威夫特没有办法做到这一点。但是,您可以在测试目标中的Objective-C文件中公开该属性,然后将其放在测试目标的桥接头中。

Add MyVC+Tests.h to your test target:

添加MyVC +测试。h到你的测试目标:

@interface MyVC (Tests)
  @property (nonatomic, weak) IBOutlet UILabel *titlelabel;
@end

MyAppTests-Bridging-Header.h

MyAppTests-Bridging-Header.h

#import "MyVC+Tests.h"

Then, in your Swift code in the test target, you can use the titleLabel property as expected.

然后,在测试目标的Swift代码中,可以按照预期使用titleLabel属性。

let vc = MyVC()
vc.titleLabel.text = "Hello, world!"

#3


0  

You can do the same property-in-category trick from the Bridging Header file. Just forward any class that calls swift library. That should take care of the problem.

您可以从桥接头文件中执行相同的属性-in-category技巧。只要转发任何调用swift库的类。那应该能解决这个问题。