首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 其他教程 > 操作系统 >

Ios运用按钮自定义segmentcontrol

2012-09-02 
Ios使用按钮自定义segmentcontrol//Author:smilelance//From:http://blog.csdn.net/smilelance#import PD

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


热点排行