想实现iPhone的RadioButton,但是又不想继承UIButton或者自定义RadioButton,于是想写个类来管理
//
// NRRadioButtonDelegate.h
//
//
// Created by rorger on 12-2-24.
// Copyright 2012年 __MyCompanyName__. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <Foundation/NSArray.h>
@interface NRRadioButtonDelegate : NSObject{
NSMutableArray *buttons;
UIImage *selectedImage;
UIImage *deselectedImage;
}
@property (nonatomic, retain) NSMutableArray *buttons;
- (void)addButton:(UIButton *)button ;
- (void)setSelectedImage:(UIImage *)image ;
- (void)setDeselectedImage:(UIImage *)image ;
- (void)setSelectedAtIndex:(int)index;
@end
//
// NRRadioButtonDelegate.m
//
//
// Created by rorger on 12-2-24.
// Copyright 2012年 __MyCompanyName__. All rights reserved.
//
#import "NRRadioButtonDelegate.h"
@implementation NRRadioButtonDelegate
@synthesize buttons;
- (id)init
{
self = [super init];
if (self) {
}
return self;
}
- (void)addButton:(UIButton *)button{
[buttons addObject:button];
[button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
}
- (void)buttonPressed:(id)sender{
UIButton *buttonPressed = (UIButton *)sender;
int index = [buttons indexOfObject:buttonPressed];
[self setSelectedAtIndex:index];
}
- (void)setSelectedImage:(UIImage *)image{
[image retain];
[selectedImage release];
selectedImage = image ;
}
- (void)setDeselectedImage:(UIImage *)image{
[image retain];
[deselectedImage release];
deselectedImage = image;
}
- (void)setSelectedAtIndex:(int)index{
for (int i=0; i< [buttons count]; i++) {
UIButton *button = (UIButton *)[buttons objectAtIndex:i];
if(i==index){
[button setBackgroundImage:selectedImage forState:UIControlStateNormal];
[button setBackgroundImage:selectedImage forState:UIControlStateHighlighted];
}
else{
[button setBackgroundImage:deselectedImage forState:UIControlStateNormal];
[button setBackgroundImage:deselectedImage forState:UIControlStateHighlighted];
}
}
}
@end
radioButtonDelegate1 = [[NRRadioButtonDelegate alloc]init];
radioButtonDelegate1.buttons = [[NSMutableArray alloc]initWithCapacity:3];
[radioButtonDelegate1 addButton:buttonPlunder];
[radioButtonDelegate1 addButton:buttonDestroy];
[radioButtonDelegate1 addButton:buttonHelp];
[radioButtonDelegate1 setSelectedImage:imageChoiceHighlited];
[radioButtonDelegate1 setDeselectedImage:imageChoice];
[radioButtonDelegate1 setSelectedAtIndex:2];