自定義pickerview

今天寫了一個自定義的pickerview,是關(guān)于時間選擇的,先上圖,有興趣的朋友可以看看.


先創(chuàng)建一個model.

#import <Foundation/Foundation.h>
@interface KKDatePickerViewModel : NSObject
@property (nonatomic,copy)NSString *year;
@property (nonatomic,copy)NSString *moth;
@property (nonatomic,copy)NSString *day;
@end```
這個model就是用于記錄當(dāng)前選擇的年月日.
然后是自定義pickerview.
#####KKDatePickerView.h

import <UIKit/UIKit.h>

import "KKDatePickerViewModel.h"

@interface KKDatePickerView : UIView
@property (strong, nonatomic) UIPickerView *pickerView;
@property (nonatomic, strong)KKDatePickerViewModel *model ;
-(instancetype)initWithFrame:(CGRect)frame;
@end

#####KKDatePickerView.m

import "KKDatePickerView.h"

@interface KKDatePickerView ()<UIPickerViewDataSource,UIPickerViewDelegate>
{
NSMutableArray *_yearArray;
NSMutableArray *_mothArray;
NSMutableArray *_dayArray ;
UIView *_view;
}

@end

@implementation KKDatePickerView

-(instancetype)initWithFrame:(CGRect)frame{

if (self=[super initWithFrame:frame]) {
    self.backgroundColor = [UIColor whiteColor];
    
    [self initData];
    [self initView];
}
return self;

}
//得到年月日這些數(shù)組
-(void)initData{

NSArray *array = [self getSystemTime];
self.model = [[KKDatePickerViewModel alloc] init];
self.model.year = array[0];
self.model.moth = array[1];
self.model.day = array[2];

_yearArray = [NSMutableArray array];
NSString *yearSystem = array[0];
int yearCount = [yearSystem intValue];
for (int i = 1900; i<yearCount+1; i++) {
    NSString *year = [NSString stringWithFormat:@"%.2d",i];
    [_yearArray addObject:year];
}
_mothArray = [NSMutableArray array];
for (int i = 1; i<13; i++) {
    NSString *moth = [NSString stringWithFormat:@"%.2d",i];
    [_mothArray addObject:moth];
}

[self getDaysInMoth:[self.model.moth integerValue]];

}
//初始化pickerview
-(void)initView{

UILabel * titleLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, self.bounds.size.width, 25)];
titleLab.text = @"選擇時間";
titleLab.textAlignment = NSTextAlignmentCenter;
titleLab.font = [UIFont systemFontOfSize:14];
titleLab.textColor = [UIColor colorWithRed:107/255.f green:107/255.f blue:107/255.f alpha:1];
[self addSubview:titleLab];

_pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(25, 35, self.bounds.size.width-50, 80)];
_pickerView.backgroundColor = [UIColor clearColor];

_pickerView.delegate = self;
_pickerView.dataSource = self;

NSArray *array = [self getSystemTime];
NSString  *yearRow = array[0] ;
int year = [yearRow intValue]-1900;

NSString *mothStr = array[1];
int moth = [mothStr intValue];

NSString *dayStr = array[2];
int day = [dayStr intValue];


//  設(shè)置默認(rèn)選中日期,即現(xiàn)在的日期
[self.pickerView selectRow:year inComponent:0 animated:YES];
[self.pickerView selectRow:(moth-1) inComponent:1 animated:YES];
[self.pickerView selectRow:(day-1) inComponent:2 animated:YES];

[self performSelector:@selector(selectSystemTime)  withObject:nil afterDelay:.1];
[self clearSeparatorWithView:_pickerView];

//_pickerview的背景色為透明,在選中的那行上面放一層view,然后設(shè)置view的背景色
UIView * selectViewBac = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width-50, 20)];
selectViewBac.backgroundColor = [UIColor colorWithRed:226/255.f green:242/255.f blue:250/255.f alpha:1];
selectViewBac.center = _pickerView.center;

[self addSubview:selectViewBac];
[self addSubview:self.pickerView];

UIColor * color = [UIColor colorWithRed:37/255.f green:162/255.f blue:219/255.f alpha:1];
UIButton * cancleBtn = [[UIButton alloc] initWithFrame:CGRectMake(30, CGRectGetMaxY(_pickerView.frame)+10, 90, 30)];
[cancleBtn setTitle:@"取消" forState:0];
[cancleBtn setTitleColor:color forState:0];
cancleBtn.layer.cornerRadius = 4;
cancleBtn.titleLabel.font = [UIFont systemFontOfSize:14];
cancleBtn.layer.masksToBounds = YES;
cancleBtn.layer.borderColor = color.CGColor;
cancleBtn.layer.borderWidth = 1;
[self addSubview:cancleBtn];

UIButton * sureBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.bounds.size.width -120, CGRectGetMaxY(_pickerView.frame) +10, 90, 30)];
[sureBtn setTitle:@"確定" forState:0];
sureBtn.titleLabel.font = [UIFont systemFontOfSize:14];
[sureBtn setTitleColor:[UIColor whiteColor] forState:0];
sureBtn.layer.cornerRadius = 4;
sureBtn.layer.masksToBounds = YES;
sureBtn.backgroundColor = color;
[self addSubview:sureBtn];

}

-(void)selectSystemTime{
NSArray *array = [self getSystemTime];
NSString *yearRow = array[0];
int year = [yearRow intValue]-1900;

NSString *mothStr = array[1];
int moth = [mothStr intValue];

NSString *dayStr = array[2];
int day = [dayStr intValue];
//得到選中的那個view,并獲取到它上面的label,再改變label的字體顏色
UIView * yearview =  [_pickerView viewForRow:year forComponent:0];
UILabel * yearlabel = yearview.subviews.firstObject;
yearlabel.textColor =[UIColor colorWithRed:13/255.f green:152/255.f blue:215/255.f alpha:1];

UIView * mothview =  [_pickerView viewForRow:(moth-1) forComponent:1];
UILabel * mothlabel = mothview.subviews.firstObject;
mothlabel.textColor =[UIColor colorWithRed:13/255.f green:152/255.f blue:215/255.f alpha:1];

UIView * dayview =  [_pickerView viewForRow:(day-1) forComponent:2];
UILabel * daylabel = dayview.subviews.firstObject;
daylabel.textColor =[UIColor colorWithRed:13/255.f green:152/255.f blue:215/255.f alpha:1];

}

pragma mark pickerviewDelegate

//返回列數(shù)
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 3;
}
//返回每列行數(shù)
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
if (component==0) {
return _yearArray.count;
} else if(component==1){

    return  _mothArray.count;
}
return _dayArray.count;

}
//每行高度

  • (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
    return 20;
    }
    //每個item的寬度
  • (CGFloat) pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component{
    if (component==0) {
    return (self.bounds.size.width-50)/3;
    } else if(component==1){
    return (self.bounds.size.width-50)/3;
    }
    return (self.bounds.size.width-50)/3;
    }

//改變選中那行的字體和顏色

  • (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    if (!view){
    view = [[UIView alloc]init];
    }
    UILabel *text = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, (self.bounds.size.width-50)/3, 20)];
    if (component == 2) {
    NSInteger selecrDay = [_pickerView selectedRowInComponent:component];
    if (selecrDay == row) {
    text.textColor = [UIColor colorWithRed:13/255.f green:152/255.f blue:215/255.f alpha:1];
    }
    }
    text.textAlignment = NSTextAlignmentCenter;
    if (component==0) {
    text.text = [_yearArray objectAtIndex:row];
    }
    if (component==1) {
    text.text = [_mothArray objectAtIndex:row];
    }
    if (component==2) {
    text.text = [_dayArray objectAtIndex:row];
    }
    [view addSubview:text];

    return view;
    }

//被選擇的行
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
//滑動月份時,更新日
if (component ==1) {
NSInteger moth = [_mothArray[row] integerValue];
[self getDaysInMoth:moth];
[_pickerView reloadComponent:2];

}

UIView * view =  [_pickerView viewForRow:row forComponent:component];
UILabel * label = view.subviews.firstObject;
label.textColor =[UIColor colorWithRed:13/255.f green:152/255.f blue:215/255.f alpha:1];
if (component==0) {
    self.model.year = [_yearArray objectAtIndex:row];
}

if (component==1) {
    self.model.moth = [_mothArray objectAtIndex:row];
}
if (component==2) {
    self.model.day = [_dayArray objectAtIndex:row];
}

}
//獲取某個月的天數(shù)
-(void)getDaysInMoth:(NSInteger)moth{

int temp = 0;
if (moth ==2) {
    temp = 29;
}else if(moth == 1||moth == 3||moth == 5||moth == 7||moth == 8||moth == 10||moth == 12){
    temp = 31;
}else{
    temp = 30;
}
_dayArray = [NSMutableArray array];
for (int i = 1; i<=temp; i++) {
    NSString *day = [NSString stringWithFormat:@"%.2d",i];
    [_dayArray addObject:day];
}

}
//讓分割線背景顏色為透明

  • (void)clearSeparatorWithView:(UIView * )view
    {
    if(view.subviews != 0 )
    {
    //分割線很薄的??
    if(view.bounds.size.height < 5)
    {
    view.backgroundColor = [UIColor clearColor];
    }

      [view.subviews enumerateObjectsUsingBlock:^( UIView *  obj, NSUInteger idx, BOOL *  stop) {
          [self clearSeparatorWithView:obj];
      }];
    

    }

}
// 獲取系統(tǒng)時間
-(NSArray*)getSystemTime{

NSDate *date = [NSDate date];
NSTimeInterval  sec = [date timeIntervalSinceNow];
NSDate *currentDate = [[NSDate alloc]initWithTimeIntervalSinceNow:sec];
NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setDateFormat:@"yyyy-MM-dd"];
NSString *na = [df stringFromDate:currentDate];
return [na componentsSeparatedByString:@"-"];

}

@end

代碼里面都寫了關(guān)鍵的注釋,希望能對大家有所幫助.好了,祝大家天天開心??
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末吴菠,一起剝皮案震驚了整個濱河市隔嫡,隨后出現(xiàn)的幾起案子孽椰,更是在濱河造成了極大的恐慌,老刑警劉巖坤检,帶你破解...
    沈念sama閱讀 218,036評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡瓶殃,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,046評論 3 395
  • 文/潘曉璐 我一進(jìn)店門副签,熙熙樓的掌柜王于貴愁眉苦臉地迎上來遥椿,“玉大人,你說我怎么就攤上這事淆储」诔。” “怎么了?”我有些...
    開封第一講書人閱讀 164,411評論 0 354
  • 文/不壞的土叔 我叫張陵本砰,是天一觀的道長碴裙。 經(jīng)常有香客問我,道長灌具,這世上最難降的妖魔是什么青团? 我笑而不...
    開封第一講書人閱讀 58,622評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮咖楣,結(jié)果婚禮上督笆,老公的妹妹穿的比我還像新娘。我一直安慰自己诱贿,他們只是感情好娃肿,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,661評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著珠十,像睡著了一般料扰。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上焙蹭,一...
    開封第一講書人閱讀 51,521評論 1 304
  • 那天晒杈,我揣著相機(jī)與錄音,去河邊找鬼孔厉。 笑死拯钻,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的撰豺。 我是一名探鬼主播粪般,決...
    沈念sama閱讀 40,288評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼污桦!你這毒婦竟也來了亩歹?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,200評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎小作,沒想到半個月后亭姥,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,644評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡躲惰,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,837評論 3 336
  • 正文 我和宋清朗相戀三年致份,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片础拨。...
    茶點(diǎn)故事閱讀 39,953評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡氮块,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出诡宗,到底是詐尸還是另有隱情滔蝉,我是刑警寧澤,帶...
    沈念sama閱讀 35,673評論 5 346
  • 正文 年R本政府宣布塔沃,位于F島的核電站蝠引,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏蛀柴。R本人自食惡果不足惜螃概,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,281評論 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望鸽疾。 院中可真熱鬧吊洼,春花似錦、人聲如沸制肮。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,889評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽豺鼻。三九已至综液,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間儒飒,已是汗流浹背谬莹。 一陣腳步聲響...
    開封第一講書人閱讀 33,011評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留桩了,地道東北人附帽。 一個月前我還...
    沈念sama閱讀 48,119評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像圣猎,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子乞而,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,901評論 2 355

推薦閱讀更多精彩內(nèi)容