我是一名学习iOS的安卓程序员。我有一个Swift视图1调用一个Objective C视图2。我想要从视图2返回一个字符串到视图1。
在安卓中,我们会简单地使用view1.startActivityForResult(View2.class)
iOS中该怎么做呢?
我是一名学习iOS的安卓程序员。我有一个Swift视图1调用一个Objective C视图2。我想要从视图2返回一个字符串到视图1。
在安卓中,我们会简单地使用view1.startActivityForResult(View2.class)
iOS中该怎么做呢?
ViewController2.h - Objective-C
@protocol ViewController2Delegate <NSObject>
- (void)sendStringBack:(NSString *)aString;
@end
@interface ViewController2 : UIViewController
@property (nonatomic, weak) id<ViewController2Delegate> delegate;
@end
ViewController2.m - Objective-C
// When you want to send the string back and dismiss the view:
[self.delegate sendStringBack:theStringToSendBack];
ViewController1.swift - Swift
@objc class ViewController1: UIViewController, ViewController2Delegate {
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let viewContr = segue.destinationViewController as! ViewController2
viewContr.delegate = self
}
func sendStringBack(aString: String) {
let aVariable = aString
// do something with the string
// dismiss the view if you presented it modally
self.dismissViewController(self, animated: true, completion: nil)
// OR
// dismiss the view if you presented it with show/push
self.navigationController?.popViewControllerAnimated(true)
}
}
在具有tablewView的ViewControllerTwo中,在didSelectRowAt方法中将数据设置为全局变量并调用以下方法 self.navigationController?.popViewController(animated: true)。
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { data = dataList[indexPath.row] self.navigationController?.popViewController(animated: true) }
它将返回到ViewControllerOne。现在您需要在viewWillAppear()或viewDidAppear()方法中捕获数据。例如:
override func viewWillAppear(_ animated: Bool) { if data != ""{ // 在处理数据后,将数据值设为空。 data = "" } }
使用UIViewController+CallBack来实现此目的。
只需设置父控制器中的结果对象,子控制器将覆盖协议方法并返回任何类型的对象给父控制器。
- (id)viewUnloadWithResultObject
无需设置协议。
UIViewController *controller = [self.storyboard instantiateViewControllerWithIdentifier:@"NewViewController"];
[controller setResultBlock:^(id resultObject) {
NSLog(@"New View Controller did pop and resulting object is: %@", resultObject);
}];
[self.navigationController pushViewController:controller animated:YES];
你也可以呈现视图控制器并获得相同的结果对象
UIViewController *controller = [self.storyboard instantiateViewControllerWithIdentifier:@"NewViewController"];
[controller setResultBlock:^(id resultObject) {
NSLog(@"New View Controller did dismissed and resulting object is: %@", resultObject);
}];
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:controller];
[self.navigationController presentViewController:navController animated:YES completion:NULL];
你也可以拥有视图卸载回调方法,例如:
- (void)viewWillUnloadCallBack
- (void)viewDidUnloadCallBack
只需继承协议并在您的视图控制器中重写这些方法即可获得卸载回调。