ios中自定义button
2013-08-07 17:58 甘超波 阅读(14129) 评论(0) 编辑 收藏 举报自定义button
#import <UIKit/UIKit.h> #define KFont 15 @interface DIYButton : UIButton @property(nonatomic,copy)NSString *ctrlName; @end #import <UIKit/UIKit.h> #define KFont 15 @interface DIYButton : UIButton @property(nonatomic,copy)NSString *ctrlName; @end
自定义 view
@protocol FirstNavViewDelegate; @interface FirstNavView : UIView @property(nonatomic,retain)NSArray *data; @property(nonatomic,assign)id<FirstNavViewDelegate> delegate; - (id)initWithFrame:(CGRect)frame data:(NSArray *)adata; @end @protocol FirstNavViewDelegate <NSObject> -(void)FirstNavViewClick:(DIYButton *)btn; @end #import "FirstNavView.h" #import "InvoiceInfo.h" #define KPadding 50 #define KMinTag 10 @implementation FirstNavView - (id)initWithFrame:(CGRect)frame data:(NSArray *)adata { self = [super initWithFrame:frame]; if (self) { CGFloat width=self.bounds.size.width/adata.count; CGFloat height=self.bounds.size.height; CGFloat center=width*0.5f; for (int i=0; i<adata.count; i++) { DIYButton *btn=[[DIYButton alloc] init]; btn.bounds=CGRectMake(0, 0, width-KPadding, height); btn.center=CGPointMake(i*width+center, height*0.5f); btn.tag=KMinTag+i; [btn addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside]; [self addSubview:btn]; [btn release]; } self.data=adata;//这一句是重点 } return self; } -(void)click:(DIYButton *)btn{ if (self.delegate &&[self.delegate respondsToSelector:@selector(FirstNavViewClick:)]) { [self.delegate FirstNavViewClick:btn]; } } -(void)setData:(NSArray *)data{ if (_data!=data) { [_data release]; _data=[data retain]; for (int i=0; i<data.count; i++) { InvoiceInfo *info=data[i]; int tag=KMinTag+i; UIView *view=[self viewWithTag:tag]; if ([view isKindOfClass:[DIYButton class]]) { DIYButton *btn=(DIYButton *)view; [btn setImage:[UIImage imageNamed:info.imagUrl] forState:UIControlStateNormal]; [btn setTitle:info.name forState:UIControlStateNormal]; btn.ctrlName=info.iPad_ctrls; } } } } @end
使用 要实现
FirstNavViewDelegate这个协议
//一级导航 NSMutableArray *NavArrary=[NSMutableArray array]; path=[[NSBundle mainBundle]pathForResource:@"Pad_Menu_First" ofType:@"json"]; NSError *navError=nil; content=[NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&navError]; if (navError) { NSLog(@"读取%@错误",path); return; } NSArray *arr=[content JSONValue]; for (NSDictionary *dic in arr) { InvoiceInfo *info=[InvoiceInfo Invoice:dic]; [NavArrary addObject:info]; } FirstNavView *navFirst=[[FirstNavView alloc] initWithFrame:tpRec data:NavArrary]; navFirst.delegate=self; [self.view addSubview:navFirst]; [navFirst release];
-(void)FirstNavViewClick:(DIYButton *)btn{
NSLog(@"一级导航__%@__%@",btn.titleLabel.text,btn.ctrlName);
[selfpushNavVc:btn.ctrlName];
}
目前我正在专注NLP,请立刻加微信/QQ号 546611623, 免费送你原创《NLP高级执行师》高清视频