@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
)
}
}
|
|
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
)
}
}
|
|
protocol
EditViewControllerDelegate
{
func
editInfo(controller:
EditViewController
,newInfo:
String
)
func
editInfoDidCancer(controller:
EditViewController
)
}
|
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的该方法