Long time no blog, come a wave today. In the actual project development, I will encounter such functional requirements: I have set up the iOS UI interface, but many of the interface's sub-view with UIView, then these uiview with Uilabel and Uiimageview, and then the need for these views to have a click event, For example, a single click jumps to a controller. At first, I would like to change all of them into UIButton, but UIButton not good to add sub-view, I also want to all customize UIButton, even if the custom, in the project has been playing a good interface or to replace each one, much trouble. So it is thought that through the UIView expansion category, the method in the category provides the listener of the gesture click event, passing the event task through block. But the properties of the class declaration are useless, but it's okay to use the runtime.
The code is as follows:
Uiview+addclickedevent.h
1 //2 //uiview+addclickedevent.h3 //addclickedevent4 //5 //Created by Heyang on 16/6/6.6 //copyright©2016 year Heyang. All rights reserved.7 //8 //GitHub:https://github.com/HeYang1234567899 //Blog:Http://www.cnblogs.com/goodboy-heyangTen // One A - #import<UIKit/UIKit.h> - the @interfaceUIView (addclickedevent) - -- (void) Addclickedblock: (void(^) (IDobj)) tapaction; - + @end
Uiview+addclickedevent.m
1 //2 //UIVIEW+ADDCLICKEDEVENT.M3 //addclickedevent4 //5 //Created by Heyang on 16/6/6.6 //copyright©2016 year Heyang. All rights reserved.7 //8 //GitHub:https://github.com/HeYang1234567899 //Blog:Http://www.cnblogs.com/goodboy-heyangTen // One A - #import "uiview+addclickedevent.h" - #import<objc/message.h> the - @interfaceUIView () - -@propertyvoid(^clickedaction) (ID); + - @end + A at @implementationUIView (addclickedevent) - -- (void) Setclickedaction: (void(^) (ID)) clickedaction{ -Objc_setassociatedobject (Self,@"addclickedevent", Clickedaction, objc_association_copy_nonatomic); - } - in- (void(^) (ID)) clickedaction{ - returnObjc_getassociatedobject (Self,@"addclickedevent"); to } + -- (void) Addclickedblock: (void(^) (IDobj)) clickedaction{ theSelf.clickedaction =clickedaction; * //hy: First to determine whether there is an interactive event, if not ... All gesture interactive events will be added to the gesturerecognizers $ if(![self gesturerecognizers]) {Panax Notoginsengself.userinteractionenabled =YES; - //hy: Add Click event theUITapGestureRecognizer *tap =[[UITapGestureRecognizer alloc] initwithtarget:self action: @selector (TAP)]; + [self addgesturerecognizer:tap]; A } the } + -- (void) tap{ $ if(self.clickedaction) { $ self.clickedaction (self); - } - } the - Wuyi @end
Then in the demo to achieve this effect, Baidu Cloud Link: http://pan.baidu.com/s/1jHQkWMa Password: waq8
iOS Development Function Module--Add click events to any UIView