您的位置:首页 > 移动开发 > IOS开发

IOS的一个带动画的多项选择的控件(一)

2016-03-26 16:52 357 查看
先上效果图:



这个程序分2个层次,一个是顶部的带UITextField的bar,一个是下拉选择的view,下拉选择的view带有4个自己定义的UIView

我们先定义一个UIViewController叫MyViewController,然后顶部的bar叫TopBarView,下拉选择的view叫TypeSelectView。像UIButton的自己定义的view叫做TypeView

TypeView有两种状态,假设手指触摸到的item就是选中状态。所以TypeSelectView应该有个属性表示当前是哪个view被选中了,TypeView中有个属性叫做自己是否被选中

由于下拉框有收起和展示两种状态。所以TypeSelectedView有个属性表示自己如今在哪种状态

先来写TypeView:

#define TypeView_Width 76
#define TypeView_Height 76

@class TypeSelectView;
@interface TypeView : UIView
@property (nonatomic, assign) int typeId;
@property (nonatomic, assign) BOOL bSelected;
@property (nonatomic,strong) TypeSelectView *typesView;
@end


touch事件:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
if (!_bSelected) {//假设触摸到的这项没被选中。那么我们就要把TypeSelectView中的当前选中项的选中状态取消
if (_typesView.curSelectedView) {
_typesView.curSelectedView.bSelected = NO;
[_typesView.curSelectedView setNeedsDisplay];
}
_bSelected = YES;
_typesView.curSelectedView = self;
[self setNeedsDisplay];

}
}


然后是draw:

- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [CCommon RGBColorFromHexString:@"#c5c4cc" alpha:1.0f].CGColor);
CGFontRef contextFont = CGFontCreateWithFontName((CFStringRef)[UIFont systemFontOfSize:14].fontName);
CGContextSetFont(context, contextFont);

CFRelease(contextFont);
CGContextSetFontSize(context, 14.0);

if (_bSelected) {
//显示select的背景
UIImage* bgImage = [UIImage imageNamed:@"change_icon_touch_bg.png"];
CGRect bgRc = rect;
bgRc.origin.x = (bgRc.size.width - bgImage.size.width)/2+1.0f; //找到背景图image的左上角的x坐标
bgRc.origin.y = (bgRc.size.height - bgImage.size.height)/2;  <span style="font-family: Arial, Helvetica, sans-serif;">//找到背景图image的左上角的y坐标</span>

bgRc.size = bgImage.size;  //ui给的背景图的大小作为控件的大小
[bgImage drawInRect:bgRc];

CGContextSetFillColorWithColor(context, [CCommon RGBColorFromHexString:@"#58baff" alpha:1.0f].CGColor);  //中间填充颜色
}

//draw image
NSString* imageName = [NSString string];
NSString* text = [NSString string];

imageName = @"mbWWW.png";
if (_typeId == 0) {
text = @"web";
}else if(_typeId == 1){
text = @"weibo";
}else if(_typeId == 2) {
text = @"sina";
}else if(_typeId == 3){
text = @"sohu";
}

if (_bSelected) {
imageName = [imageName stringByReplacingOccurrencesOfString:@".png" withString:@"_touch.png"];
}
//imageName给的view里面的src image的名称,有选中和没选中两种状态
UIImage* typeImage = [UIImage imageNamed:imageName];
CGRect rc = rect;
rc.origin.x = (rc.size.width - typeImage.size.width) / 2;
rc.origin.y = 10;
rc.size = typeImage.size;
[typeImage drawInRect:rc];

//draw text 由于文字在image以下
CGPoint textPt = CGPointMake(rc.origin.x, rc.origin.y+rc.size.height+10);

[text drawAtPoint:textPt withFont:[UIFont systemFontOfSize:14.0f]];
}


代码能够在http://download.csdn.net/detail/baidu_nod/7644329下载
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: