`
jsntghf
  • 浏览: 2476151 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

自定义UISegmentedControl

    博客分类:
  • iOS
阅读更多

CustomSegmentedControl.h

 

@class CustomSegmentedControl;
@protocol CustomSegmentedControlDelegate

- (UIButton *) buttonFor:(CustomSegmentedControl *)segmentedControl atIndex:(NSUInteger)segmentIndex;

@optional
- (void) touchUpInsideSegmentIndex:(NSUInteger)segmentIndex;
- (void) touchDownAtSegmentIndex:(NSUInteger)segmentIndex;
@end

@interface CustomSegmentedControl : UIView {
    NSObject <CustomSegmentedControlDelegate> *delegate;
    NSMutableArray *buttons;
}

@property (nonatomic, retain) NSMutableArray *buttons;

- (id) initWithSegmentCount:(NSUInteger)segmentCount segmentsize:(CGSize)segmentsize dividerImage:(UIImage *)dividerImage tag:(NSInteger)objectTag delegate:(NSObject <CustomSegmentedControlDelegate> *)customSegmentedControlDelegate;

@end

 

CustomSegmentedControl.m

 

#import "CustomSegmentedControl.h"

@implementation CustomSegmentedControl
@synthesize buttons;

- (id) initWithSegmentCount:(NSUInteger)segmentCount segmentsize:(CGSize)segmentsize dividerImage:(UIImage *)dividerImage tag:(NSInteger)objectTag delegate:(NSObject <CustomSegmentedControlDelegate> *)customSegmentedControlDelegate {
    if (self = [super init]) {
        self.tag = objectTag;
        delegate = customSegmentedControlDelegate;
        self.frame = CGRectMake(0, 0, (segmentsize.width * segmentCount) + (dividerImage.size.width * (segmentCount - 1)), segmentsize.height);
        self.buttons = [[NSMutableArray alloc] initWithCapacity:segmentCount];
        CGFloat horizontalOffset = 0;
        for (NSUInteger i = 0; i < segmentCount; i++) {
            UIButton *button = [delegate buttonFor:self atIndex:i];
            [button addTarget:self action:@selector(touchDownAction:) forControlEvents:UIControlEventTouchDown];
            [button addTarget:self action:@selector(touchUpInsideAction:) forControlEvents:UIControlEventTouchUpInside];
            [button addTarget:self action:@selector(otherTouchesAction:) forControlEvents:UIControlEventTouchUpOutside];
            [button addTarget:self action:@selector(otherTouchesAction:) forControlEvents:UIControlEventTouchDragOutside];
            [button addTarget:self action:@selector(otherTouchesAction:) forControlEvents:UIControlEventTouchDragInside];
            [buttons addObject:button];
            button.frame = CGRectMake(horizontalOffset, 0.0, button.frame.size.width, button.frame.size.height);
            [self addSubview:button];
            
            if (i != segmentCount - 1) {
                UIImageView *divider = [[[UIImageView alloc] initWithImage:dividerImage] autorelease];
                divider.frame = CGRectMake(horizontalOffset + segmentsize.width, 0.0, dividerImage.size.width, dividerImage.size.height);
                [self addSubview:divider];
            }
            
            horizontalOffset = horizontalOffset + segmentsize.width + dividerImage.size.width;
        }
    }
    
    return self;
}

- (void) dimAllButtonsExcept:(UIButton *)selectedButton {
    for (UIButton *button in buttons) {
        if (button == selectedButton) {
            button.selected = YES;
            button.highlighted = button.selected ? NO : YES;
        } else {
            button.selected = NO;
            button.highlighted = NO;
        }
    }
}

- (void)touchDownAction:(UIButton *)button {
    [self dimAllButtonsExcept:button];
    
    if ([delegate respondsToSelector:@selector(touchDownAtSegmentIndex:)])
        [delegate touchDownAtSegmentIndex:[buttons indexOfObject:button]];
}

- (void)touchUpInsideAction:(UIButton *)button {
    [self dimAllButtonsExcept:button];
    
    if ([delegate respondsToSelector:@selector(touchUpInsideSegmentIndex:)])
        [delegate touchUpInsideSegmentIndex:[buttons indexOfObject:button]];
}

- (void)otherTouchesAction:(UIButton *)button {
    [self dimAllButtonsExcept:button];
}

- (void)dealloc {
    [buttons release];
    [super dealloc];
}

@end

 

CustomSegmentedControlsViewController.h

 

#import "CustomSegmentedControl.h"

@interface CustomSegmentedControlsViewController : UIViewController <CustomSegmentedControlDelegate> {

}

@end

 

CustomSegmentedControlsViewController.m

 

#import "CustomSegmentedControlsViewController.h"

#define VERTICAL_OFFSET 10.0
#define HORIZONTAL_OFFSET 10.0
#define VERTICAL_SPACING 5.0
#define VERTICAL_HEIGHT 70.0

#define TAG_VALUE 9000

static NSArray *buttons = nil;

typedef enum {
    CapLeft          = 0,
    CapMiddle        = 1,
    CapRight         = 2,
    CapLeftAndRight  = 3
} CapLocation;

@interface CustomSegmentedControlsViewController (PrivateMethods)
- (void) addView:(UIView *)subView verticalOffset:(NSUInteger)verticalOffset title:(NSString *)title;
@end

@implementation CustomSegmentedControlsViewController

- (void) awakeFromNib {
    buttons = [[NSArray arrayWithObjects:
                [NSDictionary dictionaryWithObjectsAndKeys:[NSArray arrayWithObjects:@"One", @"Two", @"Three", nil], @"titles", [NSValue valueWithCGSize:CGSizeMake(80, 47)], @"size", @"bottombarblue.png", @"button-image", @"bottombarblue_pressed.png", @"button-highlight-image", @"blue-divider.png", @"divider-image", [NSNumber numberWithFloat:14.0], @"cap-width", nil],
                [NSDictionary dictionaryWithObjectsAndKeys:[NSArray arrayWithObjects:@"One", @"Two", nil], @"titles", [NSValue valueWithCGSize:CGSizeMake(80, 47)], @"size", @"bottombarblue.png", @"button-image", @"bottombarblue_pressed.png", @"button-highlight-image", @"blue-divider.png", @"divider-image", [NSNumber numberWithFloat:14.0], @"cap-width", nil],
                [NSDictionary dictionaryWithObjectsAndKeys:[NSArray arrayWithObjects:@"One", @"Two", @"Three", nil], @"titles", [NSValue valueWithCGSize:CGSizeMake(100, 47)], @"size", @"bottombarredfire.png", @"button-image", @"bottombarredfire_pressed.png", @"button-highlight-image", @"red-divider.png", @"divider-image", [NSNumber numberWithFloat:14.0], @"cap-width", nil], 
                [NSDictionary dictionaryWithObjectsAndKeys:[NSArray arrayWithObjects:@"1", @"2", nil], @"titles", [NSValue valueWithCGSize:CGSizeMake(47, 47)], @"size", @"bottombarredfire.png", @"button-image", @"bottombarredfire_pressed.png", @"button-highlight-image", @"red-divider.png", @"divider-image", [NSNumber numberWithFloat:14.0], @"cap-width", nil], nil] retain];
}

- (void) viewDidLoad {
    [super viewDidLoad];
    
    NSDictionary *blueSegmentedControlData = [buttons objectAtIndex:0];
    NSArray *blueSegmentedControlTitles = [blueSegmentedControlData objectForKey:@"titles"];
    CustomSegmentedControl *blueSegmentedControl = [[[CustomSegmentedControl alloc] initWithSegmentCount:blueSegmentedControlTitles.count segmentsize:[[blueSegmentedControlData objectForKey:@"size"] CGSizeValue] dividerImage:[UIImage imageNamed:[blueSegmentedControlData objectForKey:@"divider-image"]] tag:TAG_VALUE delegate:self] autorelease];
    [self addView:blueSegmentedControl verticalOffset:0 title:@"Blue segmented control"];
    
    NSDictionary *anotherBlueSegmentedControlData = [buttons objectAtIndex:1];
    NSArray *anotherBlueSegmentedControlTitles = [anotherBlueSegmentedControlData objectForKey:@"titles"];
    CustomSegmentedControl *anotherBlueSegmentedControl = [[[CustomSegmentedControl alloc] initWithSegmentCount:anotherBlueSegmentedControlTitles.count segmentsize:[[anotherBlueSegmentedControlData objectForKey:@"size"] CGSizeValue] dividerImage:[UIImage imageNamed:[anotherBlueSegmentedControlData objectForKey:@"divider-image"]] tag:TAG_VALUE + 1 delegate:self] autorelease];
    [self addView:anotherBlueSegmentedControl verticalOffset:1 title:@"Another blue segmented control"];
    
    NSDictionary *redSegmentedControlData = [buttons objectAtIndex:2];
    NSArray *redSegmentedControlTitles = [redSegmentedControlData objectForKey:@"titles"];
    CustomSegmentedControl *redSegmentedControl = [[[CustomSegmentedControl alloc] initWithSegmentCount:redSegmentedControlTitles.count segmentsize:[[redSegmentedControlData objectForKey:@"size"] CGSizeValue] dividerImage:[UIImage imageNamed:[redSegmentedControlData objectForKey:@"divider-image"]] tag:TAG_VALUE + 2 delegate:self] autorelease];
    [self addView:redSegmentedControl verticalOffset:2 title:@"Red segmented control"];
    
    NSDictionary *anotherRedSegmentedControlData = [buttons objectAtIndex:3];
    NSArray *anotherRedSegmentedControlTitles = [anotherRedSegmentedControlData objectForKey:@"titles"];
    CustomSegmentedControl *anotherRedSegmentedControl = [[[CustomSegmentedControl alloc] initWithSegmentCount:anotherRedSegmentedControlTitles.count segmentsize:[[anotherRedSegmentedControlData objectForKey:@"size"] CGSizeValue] dividerImage:[UIImage imageNamed:[anotherRedSegmentedControlData objectForKey:@"divider-image"]] tag:TAG_VALUE + 3 delegate:self] autorelease];
    [self addView:anotherRedSegmentedControl verticalOffset:3 title:@"Another red segmented control"];
}

- (void) addView:(UIView *)subView verticalOffset:(NSUInteger)verticalOffset title:(NSString *)title {
    CGFloat elementVerticalLocation = (VERTICAL_HEIGHT + (VERTICAL_SPACING * 2)) * verticalOffset;
    
    UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(HORIZONTAL_OFFSET, elementVerticalLocation + VERTICAL_OFFSET, 0, 0)] autorelease];
    label.backgroundColor = [UIColor clearColor];
    label.textColor = [UIColor whiteColor];
    label.text = title;
    [label sizeToFit];
    
    [self.view addSubview:label];
    
    subView.frame = CGRectMake(HORIZONTAL_OFFSET, elementVerticalLocation + label.frame.size.height + 5 + VERTICAL_OFFSET, subView.frame.size.width, subView.frame.size.height);
    [self.view addSubview:subView];
}

- (UIImage *) image:(UIImage *)image withCap:(CapLocation)location capWidth:(NSUInteger)capWidth buttonWidth:(NSUInteger)buttonWidth {
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(buttonWidth, image.size.height), NO, 0.0);
    
    if (location == CapLeft)
        [image drawInRect:CGRectMake(0, 0, buttonWidth + capWidth, image.size.height)];
    else if (location == CapRight)
        [image drawInRect:CGRectMake(0.0 - capWidth, 0, buttonWidth + capWidth, image.size.height)];
    else if (location == CapMiddle)
        [image drawInRect:CGRectMake(0.0 - capWidth, 0, buttonWidth + (capWidth * 2), image.size.height)];
    
    UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return resultImage;
}

#pragma mark -
#pragma mark CustomSegmentedControlDelegate
- (UIButton *) buttonFor:(CustomSegmentedControl *)segmentedControl atIndex:(NSUInteger)segmentIndex {
    NSUInteger dataOffset = segmentedControl.tag - TAG_VALUE ;
    NSDictionary *data = [buttons objectAtIndex:dataOffset];
    NSArray *titles = [data objectForKey:@"titles"];
    
    CapLocation location;
    if (segmentIndex == 0)
        location = CapLeft;
    else if (segmentIndex == titles.count - 1)
        location = CapRight;
    else
        location = CapMiddle;
    
    UIImage *buttonImage = nil;
    UIImage *buttonPressedImage = nil;
    
    CGFloat capWidth = [[data objectForKey:@"cap-width"] floatValue];
    CGSize buttonSize = [[data objectForKey:@"size"] CGSizeValue];
    
    if (location == CapLeftAndRight) {
        buttonImage = [[UIImage imageNamed:[data objectForKey:@"button-image"]] stretchableImageWithLeftCapWidth:capWidth topCapHeight:0.0];
        buttonPressedImage = [[UIImage imageNamed:[data objectForKey:@"button-highlight-image"]] stretchableImageWithLeftCapWidth:capWidth topCapHeight:0.0];
    } else {
        buttonImage = [self image:[[UIImage imageNamed:[data objectForKey:@"button-image"]] stretchableImageWithLeftCapWidth:capWidth topCapHeight:0.0] withCap:location capWidth:capWidth buttonWidth:buttonSize.width];
        buttonPressedImage = [self image:[[UIImage imageNamed:[data objectForKey:@"button-highlight-image"]] stretchableImageWithLeftCapWidth:capWidth topCapHeight:0.0] withCap:location capWidth:capWidth buttonWidth:buttonSize.width];
    }
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0.0, 0.0, buttonSize.width, buttonSize.height);
    
    [button setTitle:[titles objectAtIndex:segmentIndex] forState:UIControlStateNormal];
    [button setBackgroundImage:buttonImage forState:UIControlStateNormal];
    [button setBackgroundImage:buttonPressedImage forState:UIControlStateHighlighted];
    [button setBackgroundImage:buttonPressedImage forState:UIControlStateSelected];
    button.adjustsImageWhenHighlighted = NO;
    
    if (segmentIndex == 0)
        button.selected = YES;
    return button;
}

@end

 

效果图:


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics