ios中radiobutton

#import <UIKit/UIKit.h>

@protocol RadioButtonExtDelegate;

@interface RadioButtonExt : UIView

- (id)initWithFrame:(CGRect)frame data:(NSArray *)data ;
@property(nonatomic,assign)id<RadioButtonExtDelegate> delegate;
@end

@protocol RadioButtonExtDelegate <NSObject>

-(void)RadioButton:(RadioButtonExt *)rd from:(NSInteger)from to:(NSInteger)to;

@end


#import "RadioButtonExt.h"
#import "CommonButton.h"
#define KCount 2//要显示个数
#define KMinTag 100

@interface RadioButtonExt ()
{
    CommonButton *_LastExt;
}
@end

@implementation RadioButtonExt

- (id)initWithFrame:(CGRect)frame data:(NSArray *)data 
{
    self = [super initWithFrame:frame];
    if (self) {
        int count=data.count;
        int width=frame.size.width/KCount;//没一个宽度
        int row=count%2==0?count/KCount:count/KCount+1;//多少行
        int height=frame.size.height/row;//每一行的高度
        CGRect Rowrec,hrect,rect=self.bounds;
        for (int i=0; i<row; i++) {
            CGRectDivide(rect, &Rowrec, &rect, height, CGRectMinYEdge);//分割row
            for (int j=0; j<KCount; j++) {
                if (KCount*i+j>=count) {//行中个数
                    break;
                }
                CGRectDivide(Rowrec, &hrect, &Rowrec, width, CGRectMinXEdge);
                CommonButton *rd=[[CommonButton alloc] initWithFrame:hrect];
                [rd addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
                NSString *normalBg=[[NSBundle mainBundle]pathForResource:@"radio_normal" ofType:@"png"];
                NSString *seletctBg=[[NSBundle mainBundle]pathForResource:@"radio_selected" ofType:@"png"];
                
                [rd setImage:[UIImage imageWithContentsOfFile:normalBg] forState:UIControlStateNormal];
                [rd setImage:[UIImage imageWithContentsOfFile:seletctBg] forState:UIControlStateSelected];
                rd.tag=KMinTag+KCount*i+j;
                [rd setTitle:data[KCount*i+j] forState:UIControlStateNormal];
                [self addSubview:rd];
            }
        }
    
    }
    return self;
}

-(void)click:(CommonButton *)btn{
    if (_LastExt!=btn) {
        _LastExt.selected=NO;
        btn.selected=YES;
        
        if ([self.delegate respondsToSelector:@selector(RadioButton:from:to:)]) {
            [self.delegate RadioButton:self from:_LastExt.tag-KMinTag to:btn.tag-KMinTag];
        }
        _LastExt=btn;
    }
    
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值