我已经完成了桥接,我可以将值从 .m 文件发送到 swift 文件,反之亦然。 我的问题是我无法将 UITextField 值从 swift 发送到 .m。
我的代码是
快速文件
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 文本字段的值(null)---这是我的问题 来自 Objective-C someProperty 的值
最佳答案
你正在创建一个 ViewController 类的新对象
ViewController *swiftObj = [ViewController new];
这将是一个新对象,而不是您要访问的对象。这就是它给你 nil 的原因。
您可能必须通过 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 方面:
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)")
}
关于ios - 如何快速将 UITextField 值传递给 .m 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29249003/