iPhone以委托方式实现RadioButton

想实现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];


评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值