iOS学习笔记01-自定义简单弹出pickerView

    UIPickerView平常用的地方好像也不是很多,顶多就是一些需要选择的地方,这次项目需要这一个功能,我就单独写了一个简单的demo,效果图如下:

新增主页面弹出view,在主页面添加的代码

有个小问题就是第四个直接添加在主页弹出来的view好像被导航栏给覆盖了,我还没去研究,就着急的先吧功能写了。大家谅解下

9月-03-2016 17-49-51.gif
最初版本

picker.gif

    话说我终于弄了gif了,再也不要去截图每张图都发一遍了!!
    这个demo呢,等于是可以拿来直接用的第三方了吧,只需要传数据就可以了,弹出的三个框显示的数据也不一样,我的封装能力不行,所以都是单独写了,在这里呢,我先把链接发上,大家要是没有耐心的其实可以直接看demo,下载了,看下代码基本上就会了。YLSPicker

    实现的基本思路呢,其实也挺简单的。我这里就说下我实现的过程,然后贴上代码片段,大家可以看一下。

第一步:主页面的设置


    这里其实也没啥好说的,页面上三个不能输入的三个文本框,然后点击会弹出东西来。

1
2
//宏定义
#define YLSRect(x, y, w, h) CGRectMake([UIScreen mainScreen].bounds.size.width * x, [UIScreen mainScreen].bounds.size.height * y, [UIScreen mainScreen].bounds.size.width * w, [UIScreen mainScreen].bounds.size.height * h)


1
2
3
4
5
6
7
8
9
10
@interface ViewController ()<UITextFieldDelegate>
//声明
/** text1 */
@property (nonatomic,strong) UITextField *text1;
/** text2 */
@property (nonatomic,strong) UITextField *text2;
/** text3 */
@property (nonatomic,strong) UITextField *text3;

@end


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
   - (void)viewDidLoad {
[super viewDidLoad];
self.title = @"Picker";

//placeholder数组
NSArray *placeholderArr = @[@"Picker OneVlaue",@"Picker TwoVlaue",@"Picker ThreeVlaue"];
//循环添加文本框
for (int i = 0; i < 3; i ++)
{
UITextField *text = [[UITextField alloc]initWithFrame:YLSRect(100/375, (140 + i * 60)/667, 175/375, 30/667)];
text.borderStyle = UITextBorderStyleRoundedRect;
text.backgroundColor = [UIColor lightGrayColor];
text.tag = i + 1000;
text.placeholder = placeholderArr[i];
text.delegate = self;
[self.view addSubview:text];
if(text.tag == 1000)
{
self.text1 = text;
}else if(text.tag == 1001)
{
self.text2 = text;
}else
{
self.text3 = text;
}
}
}


    很多像我这样的新手,对textfiled的代理都不是很清楚,像我这个点击文本框不进行编辑,然后还能弹出自定义view的事件应该在哪里实现呢,答案就是在

1
2
//点击文本框时触发的事件
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField;


就这样,主页面算是勾画好了。接下来就是自定义view的部分了。

第二步:实现自定义view

    1.创建类YLSOPickerView
    2.在.h文件中声明变量,一个是需要传入的数组,一个是弹出框的标题。还要声明两个方法:

1
2
3
4
5
6
7
8
9
10
@interface YLSOPickerView : UIView
/** array */
@property (nonatomic,strong) NSArray *array;
/** title */
@property (nonatomic,strong) NSString *title;
//快速创建
+(instancetype)pickerView;
//弹出
-(void)show;
@end

    3.接下来的就是最主要的工作,就是.m文件的编写

  • 宏定义
1
2
3
4
5
6
#define YLSRect(x, y, w, h)  CGRectMake([UIScreen mainScreen].bounds.size.width * x, [UIScreen mainScreen].bounds.size.height * y, [UIScreen mainScreen].bounds.size.width * w,  [UIScreen mainScreen].bounds.size.height * h)
#define YLSFont(f) [UIFont systemFontOfSize:[UIScreen mainScreen].bounds.size.width * f]
#define YLSColorAlpha(r,g,b,a) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:(a)]
#define YLSMainBackColor [UIColor colorWithRed:240/255.0 green:239/255.0 blue:245/255.0 alpha:1]
#define BlueColor [UIColor colorWithRed:0/255.0 green:122/255.0 blue:255/255.0 alpha:1]
#define ClearColor [UIColor clearColor]
  • 声明需要用到的控件,遵守响应的协议
1
2
3
4
5
6
7
8
9
10
@interface YLSOPickerView()<UIPickerViewDelegate,UIPickerViewDataSource>
/** view */
@property (nonatomic,strong) UIView *topView;
/** button */
@property (nonatomic,strong) UIButton *doneBtn;
/** pickerView */
@property (nonatomic,strong) UIPickerView *pickerView;
/** 选择传回的值 */
@property (nonatomic,strong) NSString *result;
@end
  • 实现init方法和创建方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//快速创建
+ (instancetype)pickerView
{
return [[self alloc]init];
}

-(instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:YLSRect(0, 0, 1, 917/667)];
if (self)
{
self.backgroundColor = YLSColorAlpha(0, 0, 0, 0.4);
}
return self;
}

    这里呢我要说一下的是,为了达到在点击文本框从下弹出的一个动态效果,所以起初的时候我将整个view的长度设置成了一个屏幕的长度加上选择器的长度,在弹出方法中我将整个view上移着添加进屏幕。这样会有好看点效果

  • 添加页面控件,设置样式位置等
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
-(void)layoutSubviews
{
[super layoutSubviews];

self.topView = [[UIView alloc]initWithFrame:YLSRect(0, 667/667, 1, 250/667)];
self.topView.backgroundColor = [UIColor whiteColor];
[self addSubview:self.topView];

//为view上面的两个角做成圆角。不喜欢的可以注掉
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.topView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(5, 5)];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = self.topView.bounds;
maskLayer.path = maskPath.CGPath;
self.topView.layer.mask = maskLayer;

self.doneBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[self.doneBtn setTitle:@"Done" forState:UIControlStateNormal];
[self.doneBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
[self.doneBtn setFrame:YLSRect(320/375, 5/667, 50/375, 40/667)];
[self.doneBtn addTarget:self action:@selector(quit) forControlEvents:UIControlEventTouchUpInside];
[self.topView addSubview:self.doneBtn];

UILabel *titlelb = [[UILabel alloc]initWithFrame:YLSRect(100/375, 0, 175/375, 50/667)];
titlelb.backgroundColor = ClearColor;
titlelb.textAlignment = NSTextAlignmentCenter;
titlelb.text = self.title;
titlelb.font = YLSFont(20/375);
[self.topView addSubview:titlelb];

self.pickerView = [[UIPickerView alloc]init];
[self.pickerView setFrame:YLSRect(0, 50/667, 1, 200/667)];
[self.pickerView setBackgroundColor:YLSMainBackColor];
[self.pickerView setDelegate:self];
[self.pickerView setDataSource:self];
[self.pickerView selectRow:0 inComponent:0 animated:YES];
[self.topView addSubview:self.pickerView];

}

    同样,在这里我把topview的左上和右上两个角设置成了圆角也就是为了好看点,其实没啥区别,用的时候可以根据自己的需求来注释掉啥的。

  • 实现pickerView的协议方法
1
<UIPickerViewDelegate,UIPickerViewDataSource>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// 返回选择器有几列.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}

// 返回每组有几行
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return [self.array count];
}

#pragma mark - 代理
// 返回第component列第row行的内容(标题)
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return self.array[row];
}

// 选中第component第row的时候调用
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
self.result = self.array[row];
}
  • 先现实show方法,然后实现点击按钮Done的推出方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//弹出
- (void)show
{
[self showInView:[UIApplication sharedApplication].keyWindow];
}

//添加弹出移除的动画效果
- (void)showInView:(UIView *)view
{
// 浮现
[UIView animateWithDuration:0.5 animations:^{
CGPoint point = self.center;
point.y -= 250;
self.center = point;
} completion:^(BOOL finished) {
}];
[view addSubview:self];
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
-(void)quit
{
[UIView animateWithDuration:0.5 animations:^{
self.alpha = 0;
CGPoint point = self.center;
point.y += 250;
self.center = point;
} completion:^(BOOL finished) {
if (!self.result) {
self.result = self.array[0];
}
NSLog(@"%@",self.result);
[[NSNotificationCenter defaultCenter]postNotificationName:@"value" object:self.result];
[self removeFromSuperview];
}];
}

    在这里呢,需要注意的是,假设你没有点击,没有滑动的话,self.result是空值,所以需要你判断下,若为空,传入数组第一个数据,不为空的话就直接传递了,另外我用的是通知传值,因为block传值我还没有去学习了解,所以这里就用上我会的一个通知传值,但是我有个小问题,希望看到的人回答下我,通知一般在什么时候移除比较好呢??

第三步:主页实现点击出现的方法,并且接收回传的值。

  • 主页面引入头文件#import “YLSOPickerView.h”
  • 实现点击弹出的事件
1
2
3
4
5
6
7
8
9
10
11
12
13
#pragma mark - UITextFieldDelegate
//点击文本框时触发的事件,唤起跳出视图
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
if(textField.tag == 1000)
{
YLSOPickerView *picker = [[YLSOPickerView alloc]init];
picker.array = @[@"iPhone4",@"iPhone4S",@"iPhone5",@"iPhone5S",@"iPhone5C",@"iPhone6",@"iPhone6Plus",@"iPhone6S",@"iPhone6SPlus"];
picker.title = @"pick number";
[picker show];
}
return NO;
}
  • - (void)viewDidLoad方法中接收通知,实现通知方法
1
2
3
4
5
6
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getValue:) name:@"value" object:nil];

-(void)getValue:(NSNotification *)notification
{
self.text1.text = notification.object;
}

这样一来,一个简单的挑选单个数据的自定义选择器就算是大功告成了,使用起来有些许不方法,大家如果使用的话可以自己修改修改,此外要是有什么好的改进方法,大家也可以教教我,一起学习学习

Others


    在另外两个文本框点击出现的选择器本质上还是与上面写的一样,只是第二个数有联动效果的,第一组数据滑动的时候,第二组数据也跟着换,那我在写的时候传入的数据是字典形式的,然后另外设置两个数组将字典里的数据接收了,当然,开始就传数组形式的数据也可以,只需要在协议方法里面修改响应的代码就可以了。其他没什么变化。
传值的时候
    第三个文本框也同样与前两个本质上行没有啥区别,只是在上面多了一个随机按钮,随机按钮点击事件实现也挺简单的

1
2
3
4
5
6
self.ranBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[self.ranBtn setTitle:@"Random" forState:UIControlStateNormal];
[self.ranBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
[self.ranBtn setFrame:YLSRect(5/375, 5/667, 100/375, 40/667)];
[self.ranBtn addTarget:self action:@selector(random:) forControlEvents:UIControlEventTouchUpInside];
[self.topView addSubview:self.ranBtn];
1
2
3
4
5
6
7
8
9
10
11
12
13
-(void)random:(UIPickerView *)picker
{
for (int i = 0; i < 3; i++)
{
// 取出第i列的行数
NSInteger count = [self.array[i] count];
int random = arc4random_uniform((u_int32_t)count);
//不会触发代理的选中方法
[self.pickerView selectRow:random inComponent:i animated:YES];
//label数据刷新
[self pickerView:picker didSelectRow:random inComponent:i];
}
}

这就ok了

新增

在热心网友的提醒下,告知直接在页面添加也可以,我就添加上去了,然后还有评论说可以直接textfield的inputview设置成pickerview,这个可以的,之前我也写过的,但是刚才粗糙的加了个主页面的view,还没有去写inputview上的pickerview,等有时间再添加上去。另外也添加了dealloc方法,移除通知了。
    
这边就是我所有的思路和大部分的代码,虽然感觉没啥用处,但是新手学习的话还是有些意思的。以上的demo呢,还有很多没有完善的地方,要是大家有意见或者建议,留言评论下,讨论下应该怎么改怎么优化啥的,我很欢迎的,希望大家可以一起学习啥的。也希望我自己能经常写出一些对大家有帮助的代码。