利用delegate实现两个Controller之间的传值
RootViewController中用个lable和一个按钮,点击按钮跳转到模态窗口。在模态窗口中有个TextField和一个按钮,输入文字点击关闭模态按钮后跳转到RootViewController,并改变其label为输入的值。
- AppDelegate.swift
// AppDelegate.swift
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate{
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window?.backgroundColor = UIColor.darkGrayColor()
self.window?.makeKeyAndVisible()
let rootVc = RootViewController()
self.window?.rootViewController = rootVc
return true
}
- RootViewController.swift
import UIKit
//实现ModeViewControlDelegate协议
class RootViewController: UIViewController,MdoeViewControlDelegate{
var btn:UIButton?
var label:UILabel?
//实现协议中的方法
func changeLabel(newString:String) {
self.label!.text = newString
}
func btnOnClick(){
print("Onclick")
let modeView = ModeViewController()
//设置modeView中的代理为RootViewController自身
modeView.delegate=self
//跳转到ModelView
self.presentViewController(modeView,
animated: true ,
completion: {
print("OK")
})
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.grayColor()
label = UILabel()
label!.frame = CGRectMake(110, 40, 100, 20)
label!.backgroundColor = UIColor.greenColor()
label!.text = "你好!"
label!.textAlignment = .Center
btn = UIButton()
btn!.frame = CGRectMake(110, 80, 100, 20)
btn!.backgroundColor = UIColor.greenColor()
btn!.setTitle("下一视图", forState: .Normal)
btn!.addTarget(self, action:#selector(RootViewController.btnOnClick), forControlEvents: .TouchUpInside)
self.view.addSubview(label!)
self.view.addSubview(btn!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
- ModeViewControler.swift
import UIKit
class ModeViewController: UIViewController {
var textF:UITextField?
var delegate:MdoeViewControlDelegate?
//点击事件
func btnOnClick(){
let str = textF?.text
print(str)
// 调用代理函数 改变label值
self.delegate?.changeLabel(str!)
//返回RootView
self.dismissViewControllerAnimated(true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor=UIColor.cyanColor()
textF=UITextField()
textF!.frame=CGRectMake(110,40,100,20)
textF!.backgroundColor=UIColor.greenColor()
textF!.borderStyle = .RoundedRect
let btn=UIButton(frame:CGRectMake(110,80,100,20))
btn.backgroundColor=UIColor.greenColor()
btn.setTitle("返回上视图",forState:.Normal)
//绑定事件
btn.addTarget(self,action:#selector(ModeViewController.btnOnClick),forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(btn)
self.view.addSubview(textF!)
// Do any additional setup after loading the view.
}
}
- Protocol.swift
import Foundation
//协议定义要实现的方法
protocol MdoeViewControlDelegate {
func changeLabel(neString:String)
}