IOS development: Use Block to pass values between two interfaces (Block advanced usage: Block to pass values)
There are many places where Block is used, and the value in the Block is only a small part. The following describes the value transfer between the two interfaces of the Block:
Let's talk about the idea:
First, create two view controllers and create a UILabel and a UIButton In the first view controller. UILabel is used to display the strings passed by the second view controller, UIButton is used to push to the second interface.
The second interface only has one UITextField, which is used to input text. When the input text and the first interface are returned, when the second view is about to disappear, the text in TextFiled on the second interface is sent to the first interface and displayed on UILabel.
In fact, the core code is just a few lines of code:
The following is the main code: (because I am creating a project with storyBoard, the above attributes and corresponding methods use the outlet generated by the system)
1. Define Block attribute declaration in the. h file of the second view Controller
typedef void (^ReturnTextBlock)(NSString *showText);@interface TextFieldViewController : UIViewController@property (nonatomic, copy) ReturnTextBlock returnTextBlock;- (void)returnText:(ReturnTextBlock)block;@end
The first line of code is to redefine a name for the Block to be declared.
ReturnTextBlock
In this way, the following will be very convenient to use.
The third row is a defined Block attribute.
The fourth line is a function that passes in a Block statement Block on the first interface. This is not required, but it will reduce the amount of code written.
Ii. method for implementing the second view Controller
- (void)returnText:(ReturnTextBlock)block { self.returnTextBlock = block;}- (void)viewWillDisappear:(BOOL)animated { if (self.returnTextBlock != nil) { self.returnTextBlock(self.inputTF.text); }}
InputTF is the UITextField in the view.
The first method is the defined method, which saves the passed Block statement Block to the instance variable returnTextBlock (. h), and then find a time to call, and this time is as mentioned above, when the view is about to disappear, you need to rewrite:
- (void)viewWillDisappear:(BOOL)animated;
Method.
3. Obtain the second view controller in the first view and use the second view controller to call the defined attributes.
Write in the following method:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{ // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. TextFieldViewController *tfVC = segue.destinationViewController; [tfVC returnText:^(NSString *showText) { self.showLabel.text = showText; }];}