標籤:ios 多項選擇
先上:
這個程式分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]];}