[plain]
[plain]
每次使用UIButton的點擊事件都要新寫一個方法,感覺太麻煩,今天下來無事就用block封裝了一下button的操作事件,這樣以後能省下一些時間,而且代碼量也減少了不少。
下面我寫上源碼:
我寫的是UIButton的類目
h文件:
[plain]
<p class="p1"><span class="s1">#import </span><UIKit/UIKit.h></p><p class="p2">
</p><p class="p3"><span class="s2">typedef</span> <span class="s2">void</span> (^ActionBlock)();</p><p class="p3"><span class="s2">typedef</span> <span class="s2">void</span> (^Block_SureEvent)();</p><p class="p2">
</p><p class="p3"><span class="s2">@interface</span> UIButton (Block)<<span class="s3">UIAlertViewDelegate</span>></p><p class="p3">-(<span class="s2">void</span>)handleClickEvent:(<span class="s3">UIControlEvents</span>)aEvent withClickBlick:(<span class="s4">ActionBlock</span>)buttonClickEvent;</p><p class="p3">-(<span class="s2">void</span>)AlertViewTitle:(<span class="s3">NSString</span> *)aTitle message:(<span class="s3">NSString</span> *)aMsg cancleButtonTitle:(<span class="s3">NSString</span> *)aButtonTitle sureButtonTitle:(<span class="s3">NSString</span> *)aSureButton sureBlockEvent:(<span class="s4">Block_SureEvent</span>)aSureEvent;</p><p class="p4">@end</p>
下面是m文件
[objc]
#import "UIButton+Block.h"
#import <objc/runtime.h>
static charchar *overViewKey;
@implementation UIButton (Block)
-(void)handleClickEvent:(UIControlEvents)aEvent withClickBlick:(ActionBlock)buttonClickEvent
{
objc_setAssociatedObject(self, &overViewKey, buttonClickEvent, OBJC_ASSOCIATION_COPY_NONATOMIC);
[self addTarget:self action:@selector(buttonClick) forControlEvents:aEvent];
}
-(void)buttonClick
{
ActionBlock blockClick = objc_getAssociatedObject(self, &overViewKey);
if (blockClick != nil)
{
blockClick();
}
}
@end
其中要想使用關聯對象的objc_setAssociatedObject和objc_getAssociatedObject必須引用頭文件objc/runtime.h
objc_setAssociatedObject的四個參數分別為:源對象,key[必須是 static char類型],關聯對象,關聯方式【與修飾屬性類似】
objc_getAssociatedObject的兩個參數:源對象,key。通過這兩個參數可以獲取關聯的對象。
--------------------------------AlertView----------------------Block-----------------------------------------
[objc]
<p class="p1"><span class="s1">static</span> <span class="s1">char</span> * alertKey;</p>
[objc]
-(void)AlertViewTitle:(NSString *)aTitle message:(NSString *)aMsg cancleButtonTitle:(NSString *)aButtonTitle sureButtonTitle:(NSString *)aSureButton sureBlockEvent:(Block_SureEvent)aSureEvent
{
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:aTitle message:aMsg delegate:self cancelButtonTitle:aButtonTitle otherButtonTitles:aSureButton, nil nil];
objc_setAssociatedObject(self, &alertKey, aSureEvent, OBJC_ASSOCIATION_COPY_NONATOMIC);
[alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 1)
{
Block_SureEvent blockSure = objc_getAssociatedObject(self, &alertKey);
if (blockSure != nil)
{
blockSure();
}
else
{
NSLog(@"error");
}
}
}