#import <UIKit/UIKit.h>數組
@protocol MenuProtocol <NSObject>ide
@optional字體
-(void)getTag:(NSInteger)tag;atom
@end spa
@interface MenuView : UIView{.net
NSArray*_MenuArray;//菜單名數組3d
}orm
-(void)onClick:(NSInteger)tag;get
-(void)setNameWithArray:(NSArray*)menuArray;//設置菜單名方法animation
@property(nonatomic,assign)id<MenuProtocol>MyDelegate;
@end
@implementation MenuView
-(void)setNameWithArray:(NSArray *)menuArray
{
_MenuArray=menuArray;
CGFloat Space=self.frame.size.width/[_MenuArray count];
for (int i=0; i<[menuArray count]; i++) {
if (i>0)
{
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(Space*i, 0, 2, self.frame.size.height)];
label.backgroundColor = [UIColor whiteColor];
[self addSubview:label];
}
UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
btn.frame=CGRectMake(Space*i, 0, Space, self.frame.size.height);
btn.tag=i;
if (btn.tag==0)
{
btn.enabled=NO;
}
//字體大小顏色狀態
NSMutableAttributedString *str=[[NSMutableAttributedString alloc]initWithString:[menuArray objectAtIndex:i]];
[str addAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:15],NSForegroundColorAttributeName:[UIColor grayColor]} range:NSMakeRange(0, [str length])];
[btn setAttributedTitle:str forState:UIControlStateNormal];
NSMutableAttributedString *selStr=[[NSMutableAttributedString alloc]initWithString:[menuArray objectAtIndex:i]];
[selStr addAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:15],NSForegroundColorAttributeName:col} range:NSMakeRange(0, [str length])];
[btn setAttributedTitle:selStr forState:UIControlStateDisabled];
[btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:btn];
}
//底部劃線
UIView *markline=[[UIView alloc]initWithFrame:CGRectMake(0, self.frame.size.height-2, Space+1, 2.0)];
markline.tag=999;
markline.backgroundColor=col;
[self addSubview:markline];
}
-(void)btnClick:(UIButton*)sender{
[self onClick:sender.tag];
if ([self.MyDelegate respondsToSelector:@selector(getTag:)]) {
[self.MyDelegate getTag:sender.tag];
}
}
-(void)onClick:(NSInteger )tag
{
for (UIView*subview in self.subviews) {
if ([subview isKindOfClass:[UIButton class]]) {
UIButton *subBtn=(UIButton*)subview;
if (subBtn.tag==tag) {
[subBtn setEnabled:NO];
}else{
[subBtn setEnabled:YES];
}
}
}
CGFloat Space=self.frame.size.width/[_MenuArray count];
UIView *markview=[self viewWithTag:999];
[UIView animateWithDuration:0.2f animations:^{
CGRect markFrame=markview.frame;
markFrame.origin.x=tag*Space;
markview.frame=markFrame;
}];
}
@end
-(void)getTag:(NSInteger)tag{
if (tag == 0) {
[_MyScrollView setContentOffset:CGPointMake(0.0, 0.0) animated:YES];
}
else
{
[_MyScrollView setContentOffset:CGPointMake(mainScreen.size.width+50, 0.0) animated:YES];
}