1. Through the encapsulation of the button, thus reducing the amount of code, we do not need a large paragraph to create a button, as long as through the encapsulated button class can be created, here we use block to encapsulate.
(1) First create a class that inherits the Button class
(2) then define block
(3) Defining class methods
(4) Implementing a class method in. m
2. The specific code is as follows:
(1) in the. h file
#import <UIKit/UIKit.h>
@class Mgbutton;
typedef void (^block) (Mgbutton *button);
@interface Mgbutton:uibutton
+ (Mgbutton *) Buttonwithframe: (CGRect) frame type: (uibuttontype) type title: (NSString *) title Addblock: (Block) Tempblock;
@end
(2) Implementing a class method in a. m file
#import "MGButton.h"
@interface Mgbutton ()
Note: To write composite access to the block variable, be sure to use copy
@property (nonatomic,copy) block Myblock;
@end
@implementation Mgbutton
Generating a button object using block
+ (Mgbutton *) Buttonwithframe: (CGRect) frame type: (uibuttontype) type title: (NSString *) title Addblock: (Block) Tempblock {
Mgbutton *button = [Mgbutton buttonwithtype:type];
[Button Settitle:title Forstate:uicontrolstatenormal];
Button.frame = frame;
[Button Addtarget:button action: @selector (buttoncilcked:) forcontrolevents:uicontroleventtouchupinside];
Button.myblock = Tempblock;
return button;
}
Button's Click event
-(void) buttoncilcked: (Mgbutton *) button {
NSLog (@ "Here is the interior of the Buttoncilcked method");
Trigger button
Button.tag = 10;
Button.myblock (button);
}
@end
3. Create a button, you can introduce the Mgbutton header file, through the class method to create a button
The code is as follows:
UIButton *btn = [Mgbutton buttonwithframe:cgrectmake (0, 0, $) type:uibuttontypecustom title:@ "button" addblock:^ ( Mgbutton *button) {
NSLog (@ "button click event");
}];
[Self.view ADDSUBVIEW:BTN];
4. Other forms of the button can be customized according to the needs of your project, the implementation of the Block method.
Package for Button