The implementation example consists of two interfaces
A B two views
A-> B uses the attribute to pass the value
B-> A reverse callback value using closures
The principle of Swift's use of the value of a closure is similar to that of the code block (block) used in OC.
Follow these steps to understand:
1, define closures.
2, Closure assignment (transfer)
3, closure call.
To perform an operation on the current interface, it is defined on the current interface,
For example: I want to pass the B interface callback to the A Interface label assignment, the assignment is executed on the A interface, then the closure should be defined on the A interface. Since the definition is in A, then the B interface is where the closure is called. Find the implementation, followed by the caller, and then define the properties in the caller interface to receive closures;
Implementation code:
Import UIKit
class Viewcontroller:uiviewcontroller {
//Lazy load add BTN
lazy var Btn:uibutton = {
let button = UIButton (Frame:cgrectmake (100, 200, 100, 30))
Button.backgroundcolor = Uicolor.redcolor ()
Button.addtarget (Self, Action: "Btnaction:", forControlEvents: uicontrolevents.touchupinside)
button.settitle ("Click to jump Page", Forstate: Uicontrolstate.normal)
return button
} ()
Lazy Loading method Add label
Lazy var Label:uilabel = {
Let lab = UILabel (frame:cgrectmake (100, 100, 100, 30))
Lab.backgroundcolor = Uicolor.yellowcolor ()
Return Lab
} ()
BTN Implementation method
Func btnaction (Btn:uibutton) {
Let SECVC = Secviewcontroller ()
Property Pass-value assignment
Secvc.str = Label.text
Receive the value passed over
Secvc.sendvalue = {
(str:string), () in
Self.label.text = str
}
Present to B interface
Self.presentviewcontroller (SECVC, Animated:true, Completion:nil)
}
Override Func Viewdidload () {
Super.viewdidload ()
View.addsubview (BTN)
View.addsubview (label)
}
}
Import UIKit
Class Secviewcontroller:uiviewcontroller {
Attribute passing value definition variable
var str:string?
Variable: Type Here the type is a closure
var Sendvalue: ((str:string))?
Lazy Loading Add TextField
Lazy var Textfield:uitextfield = {
Let tf = Uitextfield (frame:cgrectmake (100, 100, 100, 30))
Value of property passing value
Tf.text = Self.str
Tf.backgroundcolor = Uicolor.yellowcolor ()
return TF
} ()
Lazy Loading Add btn
Lazy var Button:uibutton = {
Let btn = UIButton (Frame:cgrectmake (100, 200, 100, 30))
Btn.settitle ("Back", ForState:UIControlState.Normal)
Btn.addtarget (Self, Action: "Back", ForControlEvents:UIControlEvents.TouchUpInside)
Return BTN
} ()
BTN Implementation method
Func back () {
Call
If Sendvalue! = Nil {
sendvalue! (str:textfield.text!)
}
Self.dismissviewcontrolleranimated (True, Completion:nil)
}
Override Func Viewdidload () {
Super.viewdidload ()
View.addsubview (TextField)
View.addsubview (Button)
}
}
Swift Closure Pass Value