我已完成桥接,我可以将.m文件中的值发送到swift文件,反之亦然。 我的问题是我无法将swit的UITextField值发送到.m。
我的代码是
Swift文件
import UIKit
class ViewController: UIViewController {
@IBOutlet var txt: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
txt.text = "swift"
//---- call property and method from objective-C
var instanceOfCustomObject: CustomObject = CustomObject()
instanceOfCustomObject.someMethod()
var propertyFromObjC: AnyObject! = instanceOfCustomObject.someProperty
println("value from objective-C \(propertyFromObjC)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
和.m文件是
#import <Foundation/Foundation.h>
#import "CustomObject.h"
#import "Bridging-Swift.h"
@implementation CustomObject
- (void) someMethod {
_someProperty=@"someProperty";
NSLog(@"valueFromObjective-C method");
ViewController *swiftObj = [ViewController new];
NSLog(@"value from swift textfield %@", swiftObj.txt.text );
}
@end
结果是: valueFromObjective-C方法 来自swift textfield的值(null)---这是我的问题 来自Objective-C someProperty
的价值答案 0 :(得分:0)
您正在行
中创建ViewController类的新对象ViewController *swiftObj = [ViewController new];
这将是一个新对象,而不是您要访问的对象。这就是它给你一个零的原因。
您可能必须通过init或其他方式将ViewController的实例传递给CustomObject,以便在somemethod()中访问它。
@implementation CustomObject
- (id) initWithViewController:(ViewController*) vc {
self.vc = vc
}
- (void) someMethod {
_someProperty=@"someProperty";
NSLog(@"valueFromObjective-C method");
NSLog(@"value from swift textfield %@", self.vc.txt.text );
}
@end
Swift Side:
override func viewDidLoad() {
super.viewDidLoad()
txt.text = "swift"
//---- call property and method from objective-C
var instanceOfCustomObject: CustomObject = CustomObject(self)
instanceOfCustomObject.someMethod()
var propertyFromObjC: AnyObject! = instanceOfCustomObject.someProperty
println("value from objective-C \(propertyFromObjC)")
}