Use of iOS. UI advanced Block, ios. uiblock
Simplest block usage
Three steps to use block: 1. Define block variables 2. Create block code blocks 3. Call block anonymous Functions
Defines the composition of a block, including the return value, block name, and parameter type.
Block Code blocks can be written in other methods as an anonymous function. Therefore, we generally write block code blocks in other methods. block Code blocks will not be executed when this method is called, it is executed only when the block code block is called back.
ViewController. h
# Import <UIKit/UIKit. h>
@ Interface ViewController: UIViewController
@ Property (nonatomic, copy) void (^ myBlock) (int); // 1. Declare a block variable and directly declare the block as an attribute variable, which is more convenient and practical.
@ End
ViewController. m
# Import "ViewController. h"
# Import "NewViewController. h"
@ Interface ViewController ()
@ End
@ Implementation ViewController
-(Void) viewDidLoad {
[Super viewDidLoad];
// Note: The method for loading and writing block code blocks first
[Self blockTest];
}
-(Void) blockTest {
// 2. Write block code blocks in the Method
_ MyBlock = ^ (int ){
NSLog (@ "% d", );
};
}
-(Void) touchesBegan :( NSSet *) touches withEvent :( UIEvent *) event {
// 3. Call the block anonymous Function
_ MyBlock (10 );
NewViewController * newViewController = [[NewViewController alloc] init];
NewViewController. block = _ myBlock;
[Self presentViewController: newViewController animated: YES completion: ^ {
}];
}
@ End
The above code implements three steps of block implementation in ViewController. The function of this block is to print the parameter value.
The touch method redirects from ViewController to NewViewController, and assigns the block in ViewController to the block defined in NewViewController, so that the two blocks are essentially the same block, in NewViewController, you can call the code block in ViewController.
NewViewController. h
# Import <UIKit/UIKit. h>
# Import "ViewController. h"
@ Interface NewViewController: UIViewController
@ Property (nonatomic, copy) void (^ block) (int );
@ End
NewViewController. m
# Import "NewViewController. h"
@ Interface NewViewController ()
@ End
@ Implementation NewViewController
-(Void) viewDidLoad {
[Super viewDidLoad];
Self. view. backgroundColor = [UIColor grayColor];
}
-(Void) touchesBegan :( NSSet *) touches withEvent :( UIEvent *) event {
Self. block (100 );
[Self dismissViewControllerAnimated: YES completion: ^ {
}];
}
@ End
For iOS beginners, please kindly advise if any errors exist!