读书人

Ios运用按钮自定义segmentcontrol

发布时间: 2012-09-02 21:00:34 作者: rapoo

Ios使用按钮自定义segmentcontrol

//Author:smilelance

//From:http://blog.csdn.net/smilelance

#import "PDESegmentControl.h"


#define SEGMENT_UNSELECTED 0

#define SEGMENT_SELECTED 1


@implementation PDESegmentControl


- (id)initWithFrame:(CGRect)frame

{

self = [super initWithFrame:frame];

if (self) {

// Initialization code

}

return self;

}


- (id) initWithFrame:(CGRect)frame items:(NSArray*)itemArray

{

self = [super initWithFrame:frame];

if (self) {

int segmentCount = [itemArray count];

segmentButtons = [[NSMutableArrayalloc] init];

buttonImgNames = [[NSMutableArrayalloc] init];

float segmentWidth = frame.size.width/segmentCount;

for (int i=0; i<segmentCount; i++) {

UIButton *button = [UIButtonbuttonWithType:UIButtonTypeCustom];

button.frame = CGRectMake(segmentWidth*i, 0,

segmentWidth, frame.size.height);

if (i==0) {//left

[buttonImgNamesaddObject:@"seg_btn_left_nor.png"];

[buttonImgNamesaddObject:@"seg_btn_left_sel.png"];

}else if(i==segmentCount-1){//right

[buttonImgNamesaddObject:@"seg_btn_right_nor.png"];

[buttonImgNamesaddObject:@"seg_btn_right_sel.png"];

}else{ //middle

}

button.tag = i;

[button addTarget:selfaction:@selector(segmentAction:)forControlEvents:UIControlEventTouchUpInside];

[button setTitle:[itemArrayobjectAtIndex:i] forState:UIControlStateNormal];

[segmentButtons addObject:button];

[self addSubview:button];

}

[selfsetSegmentIndex:0];

}

return self;

}


-(void)setSegmentIndex:(NSInteger)index

{

_selectedSegmentIndex = index;

[self segmentAction:[segmentButtonsobjectAtIndex:index]];

}


-(void)segmentAction:(id)sender

{

UIButton *button = (UIButton*)sender;

int tag = button.tag;

for(int i=0; i<[segmentButtonscount]; i++){

int nameOffset = SEGMENT_UNSELECTED;

if (tag == i) {

nameOffset = SEGMENT_SELECTED;

}

UIButton *segButton = [segmentButtonsobjectAtIndex:i];

[segButton setBackgroundImage:[UIImageimageNamed:[buttonImgNames objectAtIndex:i*2+nameOffset]]

forState:UIControlStateNormal];

}

}

/*

// Only override drawRect: if you perform custom drawing.

// An empty implementation adversely affects performance during animation.

- (void)drawRect:(CGRect)rect

{

// Drawing code

}

*/


@end


读书人网 >操作系统

热点推荐