ios开发实践之UIDatePicker(已对之前无法解决的问题做了解答)

需求:要做一个生日选择的控件,但除了选择之外还需要自定义几个控件,跟生日选择控件组合一起。

做法:自定义了一个UIImageView,并且作为背景。在这个背景view上再添加其他button和时间选择器

问题及解决:1.UIDatePicker无法调整大小,必须用系统默认的大小,但可以改变位置。解决方法只有自定义实现UIPickerView,实现2个相关代理。

      2.在网上个关于UIDatePicker看到一个很搞笑的问题,就是关于如何监听UIDatePicker上的选择事件的,其实官方文档已经写得很清楚了,UIDatePicker并不是UIPickerView得子类,但持有其对象,但关于如何操纵这个对象,并没有找到相关方法,想监听其实也简单,只需下面代码而已。

 [_picker addTarget:selfaction:@selector(didPicker) forControlEvents:UIControlEventValueChanged];

添加事件即可。

      3.关于UIImageView上的userInteractionEnabled,其实在UIView上都有这个属性,但默认上都是YES,而UIImageView是NO!!,再来看看官方描述就知道蛋疼了。。:

  A Boolean value that determines whether user events are ignored and removed from the event queue.

      当时弄了好久无法滚动UIDatepicker,以为是第一响应者问题,多种无果啊,感觉类似于android上的焦点问题.

问题补充:回头做了整理,发现前面的总结1是不科学的,因为如果直接通过官方给的文档去改,确实不行,但是,如果通过其他方法呢?看来看去,之前做的那个UIDatepicker还是很丑,所以一直在想有什么方法能够解决,后来在解决一个插件的时候,得到了灵感,就是继承原来的datepicker类,并在重绘方法drawRect中对父类的view进行修改。具体代码如下:

- (void)drawRect:(CGRect)rect

{

    // Drawing code

    UIView *v1 = [[selfsubviews]objectAtIndex:0];

    UIView *v3 = [[v1 subviews]objectAtIndex:0];

    [v3 setBackgroundColor:[UIColorcolorWithRed:0.247green:0.251blue:0.251alpha:1]];

    //编辑区域上下左右边框

    UIView *v20 = [[v1 subviews]objectAtIndex:20];

    v20.alpha = 0.0;

    int i=0;

    for(UIView* v in [v1 subviews]){

        NSString *s = NSStringFromCGSize(v.frame.size);

        s = [NSString stringWithFormat:@"%d:::%@",i++,s];

        myLog(s,nil);

    }

    /*

        v2: 第一个选择器白色底高度

        v4: 第一个显示的数据高度

        v5: 第一个选择器背景高度

        v10:第二个选择器的数据高度

     v20 中间编辑框背景

     */

    UIView *v00 = [[v1 subviews]objectAtIndex:0];

    [selfchangeHeight:v00 height:130];

    

    

    UIView *v2 = [[v1 subviews]objectAtIndex:2];

   

    CGRect myFrame = v2.frame;

    myFrame.size.height = 124;

    v2.frame = myFrame;

    

    UIView *v4 = [[v1 subviews]objectAtIndex:4];

    [selfchangeHeight:v4 height:124];

    UIView *v5 = [[v1 subviews]objectAtIndex:5];

    [selfchangeHeight:v5 height:124];

    //2

    UIView *v8= [[v1 subviews]objectAtIndex:8];

    [selfchangeHeight:v8 height:124];

    UIView *v10 = [[v1 subviews]objectAtIndex:10];

    [selfchangeHeight:v10 height:124];

    UIView *v11 = [[v1 subviews]objectAtIndex:11];

    [selfchangeHeight:v11 height:124];

    

    //3

    UIView *v14= [[v1 subviews]objectAtIndex:14];

    [selfchangeHeight:v14 height:124];

    UIView *v16 = [[v1 subviews]objectAtIndex:16];

    [selfchangeHeight:v16 height:124];

    UIView *v17 = [[v1 subviews]objectAtIndex:17];

    [selfchangeHeight:v17 height:124];

    [selfsetNeedsDisplay];

}

-(void)changeHeight:(UIView*)v height:(NSInteger)height{

    CGRect myFrame = v.frame;

    myFrame.size.height = height;

    v.frame = myFrame;

}

原文地址:https://www.cnblogs.com/mapleyuan/p/3259033.html