我正在开发一个应用程序,我需要将数据传递给导航 Controller 并返回。
我使用本教程让它工作:link
在我的应用程序中,我从我的第一个 View Controller (在教程 uiviewcontroller 中)到 secondViewcontroller(在教程 fooTwoVC 中)的推送 segue 也拥有另一个 View Controller 。
那么我的问题是我可以为那个 VC 使用相同的协议(protocol)还是我需要制定另一个协议(protocol)?
import UIKit
class ViewController: UIViewController,FooTwoViewControllerDelegate {
@IBOutlet var colorLabel : UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
func myVCDidFinish(controller: FooTwoViewController, text: String) {
colorLabel.text = "The Color is " + text
controller.navigationController?.popViewControllerAnimated(true)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if segue.identifier == "mySegue"{
let vc = segue.destinationViewController as! FooTwoViewController
vc.colorString = colorLabel.text!
vc.delegate = self
}
}
}
import UIKit
protocol FooTwoViewControllerDelegate{
func myVCDidFinish(controller:FooTwoViewController,text:String)
}
class FooTwoViewController: UIViewController {
var delegate:FooTwoViewControllerDelegate? = nil
var colorString:String = ""
@IBOutlet var colorLabel : UILabel!
@IBAction func saveColor(sender : UIBarButtonItem) {
if (delegate != nil) {
delegate!.myVCDidFinish(self, text: colorLabel!.text!)
}
}
@IBAction func colorSelectionButton(sender: UIButton) {
colorLabel.text = sender.titleLabel!.text!
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
colorLabel.text = colorString
}
}
最佳答案
过了一段时间我终于弄明白了,毕竟也没那么难。
我只需要将协议(protocol)更改为:
protocol FooTwoViewControllerDelegate{
func myVCDidFinish(controller:UIViewController,text:String)
}
所以我可以被其他 View Controller 使用。 此外,我在第三个 View Controller 中使用了相同的代码。
有什么问题随时问。
关于swift - 在导航 Controller 中使用协议(protocol)委托(delegate)移动数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35259107/