Swift - 创建代理协议实现页面间参数传递和方法调用

前端之家收集整理的这篇文章主要介绍了Swift - 创建代理协议实现页面间参数传递和方法调用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在开发中,经常需要用到协议代理模式。比如,进入编辑页面修改数据后,将新数据回传到主界面。
@H_502_1@
下面通过一个样例来说明协议代理模式,功能如下:
1,主页面有一个标签和一个修改按钮,点击修改按钮会跳转到编辑页面
2,编辑页面修改输入框的文字后,点击“确定”则返回主页面,同时主页面标签值会替换成新值
3,如果点击编辑页面的“取消”按钮则直接返回主页面
@H_502_1@
效果图如下:
@H_502_1@
@H_502_1@
实现过程:
1,首先在storyboard中绘制如下两个界面,同时将主界面的“修改”按钮与编辑页做present modally关联
@H_502_1@
@H_502_1@
2,设置这个关联Segue的Identity为 EditView
@H_502_1@
@H_502_1@
3,主界面ViewController.swift
import UIKit
class ViewController : UIViewController , EditViewControllerDelegate {
@IBOutlet weak var label: UILabel !
override func viewDidLoad() {
super .viewDidLoad()
// Do any additional setup after loading the view,typically from a nib.
}
override func didReceiveMemoryWarning() {
super .didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue ,sender: AnyObject ?) {
if segue.identifier == "EditView" {
//通过seque的标识获得跳转目标
let controller = segue.destinationViewController as ! EditViewController
//设置代理
controller.delegate = self
//将值传递给新页面
controller.oldInfo = label.text
}
}
func editInfo(controller: EditViewController ,newInfo: String ){
label.text = newInfo;
//关闭编辑页面
controller.presentingViewController!.dismissViewControllerAnimated( true ,completion: nil )
}
@H_313_301@
func editInfoDidCancer(controller: EditViewController ){
//关闭编辑页面
controller.presentingViewController!.dismissViewControllerAnimated( true ,completion: nil )
}
}
@H_502_1@ 4,编辑页 EditViewController.swift
import UIKit
class EditViewController : UIViewController {
@IBOutlet weak var textField: UITextField !
var delegate: EditViewControllerDelegate ?
var oldInfo: String ?
override func viewDidLoad() {
super .viewDidLoad()
// Do any additional setup after loading the view.
if oldInfo != nil {
textField.text = oldInfo
}
}
override func didReceiveMemoryWarning() {
super .didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func done(sender: AnyObject ) {
delegate?.editInfo( self ,newInfo: textField.text!)
}
@IBAction func cancel(sender: AnyObject ) {
delegate?.editInfoDidCancer( self )
}
}
@H_502_1@ 5,编辑页代理 EditViewControllerDelegate.swift
protocol EditViewControllerDelegate {
func editInfo(controller: EditViewController ,newInfo: String )
func editInfoDidCancer(controller: EditViewController )
}
@H_502_1@ 6,在Storyboard中,将编辑页的Class设为EditViewController



presentedViewController:The view controller that is presented by this view controlller(read-only),被本视图控制器present出来的的视图控制器

presentingViewController:The view controller that presented this view controller. (read-only),present出来本视图控制器的视图控制器
如A-->弹出B,则A.presentedViewController = B
B.presentingViewController = A
dismissViewControllerAnimated:YES
Dismisses the view controller that was presented modally by the view controller.
也就是在在A上调该方法,dismiss掉A弹出的vc
如果在B上调,会调用presenting view的该方法,即A的该方法

猜你在找的Swift相关文章