下面通过一个样例来说明协议代理模式,功能如下:
效果图如下:
实现过程:
1,首先在storyboard中绘制如下两个界面,同时将主界面的“修改”按钮与编辑页做present modally关联
2,设置这个关联Segue的Identity为 EditView
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_275_301@
func
editInfoDidCancer(controller:
EditViewController
){
controller.presentingViewController!.dismissViewControllerAnimated(
true
,completion:
nil
)
}
}
|
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
)
}
}
|
5,编辑页代理 EditViewControllerDelegate.swift
|
protocol
EditViewControllerDelegate
{
func
editInfo(controller:
EditViewController
,newInfo:
String
)
func
editInfoDidCancer(controller:
EditViewController
)
}
|
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/324528.html