如何在iOS中使用Swift反转手势识别器时返回信息?

我是iOS Development和Swift的新手。 我在Google上find的许多资源都是用Objective-C编写的,而我也不熟悉它。

我有两个视图故事板,S1和S2。 他们每个人至less有一个视图控制器,VC1和VC2分别。 我使用手势识别器从S1到S2,而不是Segue。 在S2上,我select从表格视图获取的数据。 当我从表格上的列表中按下一个值时,我想把这个值发回到S1。

用Swift做这件事的最好方法是什么? 谢谢!

你可以使用NSNotificationCenter

在S1中添加Oberver

NSNotificationCenter.defaultCenter().addObserver(self, selector: "NotificationMethod:", name:"NotificationName", object: nil) func NotificationMethod(notification: NSNotification){ //Take Action on Notification } 

从S2 tableview中调用它并单击并传递userInfo。

 NSNotificationCenter.defaultCenter().postNotificationName("NotificationName", object: nil) 

您可以使用自定义协议技术。

在S1写

 @IBOutlet var textField: UITextField! @IBOutlet var datalbl: UILabel! override func viewDidLoad() { super.viewDidLoad() navigationController?.navigationBarHidden = true } func myMethod(text:String){ datalbl.text = text } @IBAction func nextViewBtn(sender:UIButton){ let nextObjvc = self.storyboard?.instantiateViewControllerWithIdentifier("S2") as! S2 nextObjvc.delegate = self self.navigationController?.pushViewController(nextObjvc, animated: true) } 

写在S2

 @IBOutlet var fullNameLabel: UILabel! var str:String = String() var myArray:NSArray = NSArray() var delegate:myProtocol? override func viewDidLoad() { super.viewDidLoad() myArray = ["APPLE","BLACKBERRY","CANON","DELEGAT","EMIT","FLAG","GENERAL"] self.fullNameLabel.text = str } 

希望这可能对你有帮助。

这样做的首选方法是使用委托 ,例如告诉S2S1报告。

另一个答案试图说明这一点,但没有明确发生了什么事情。

这个想法是让S2持有对S1的引用并回报。 这很方便,你不使用segues; 他们会使它更复杂。

协议

你可以通过创build一个通讯协议来实现:

 protocol ReportBackProtocol { func reportValues(someValues : SomeType) } 

S1

S1 ,你可以这样实现ReportBackProtocol

 class S1 : UIViewController, ReportBackProtocol { // all your S1 class things func reportValues(someValues : SomeType) { // do with the values whatever you like in the scope of S1 } 

然后,将您的S1实例作为您创buildS2实例的代理,然后将其呈现:

 let s2 = S2() s2.delegate = self // present it as you already do 

S2

S2 ,无论您编译了哪些值(我们称它们为x ),并准备好将它们发回:

 self.delegate?.reportValues(x) 

你也需要把这个委托实例variables添加到S2如下所示:

  weak var delegate : ReportBackProtocol? 

这应该做的伎俩; 请让我知道,如果你遇到问题或不理解的概念的一部分。