In development, it is often necessary to use the Protocol proxy mode. For example, after entering the edit page to modify the data, the new data is uploaded back to the main interface.
here is a sample to illustrate the Protocol proxy mode, with the following functions:1, the main page has a label and a Modify button, click the Modify button will jump to edit page 2, edit the page to modify the text of the input box, click "OK" to return to the main page, and the main page label value will be replaced by the new value 3, if you click on the edit Page "Cancel" button to return to the main page
as follows:
implementation process:1, first draw the following two interfaces in storyboard, while the main interface "Modify" button and edit page present Modally Association
2, set the identity of the edit page to EditView
3, main interface Viewcontroller.swift
123456789101112131415161718192021222324252627282930313233343536373839 |
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
)
}
func editInfoDidCancer(controller:
EditViewController
){
//关闭编辑页面
controller.presentingViewController!.dismissViewControllerAnimated(
true
, completion:
nil
)
}
}
|
4, edit page Editviewcontroller.swift
1234567891011121314151617181920212223242526272829303132 |
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, edit page Agent Editviewcontrollerdelegate.swift
1234 |
protocol EditViewControllerDelegate { func editInfo(controller: EditViewController , newInfo: String ) func editInfoDidCancer(controller: EditViewController ) } |
Swift-Create proxy protocol for inter-page parameter passing and method invocation