使用UIDatePicker加载nib和实例化视图需要花费大量时间

时间:2015-03-30 10:26:33

标签: ios objective-c xib uidatepicker uinib

我有两个视图的简单xib:带日期选择器的容器视图和带有按钮的工具栏。我将输入字段inputView)用作inputAccessoryView<UIKeyInput>。但是我遇到了性能问题:我注意到加载这个xib文件的nib并从nib实例化一个视图需要大约500ms(用Time Profiler工具工具计算)。所以,不是向xib添加日期选择器,而是以编程方式创建它,并且vuela!,实例化只需要〜30ms。 代码示例非常简单:

- (void)initialize
{
    NSString * className = NSStringFromClass(self.class);
    UINib * nib = [UINib loadCachedForKey:className];
    [classNib instantiateWithOwner:self
                           options:nil];    
    _contentView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    _contentView.frame = self.bounds;
    [self addSubview:_contentView];
}

其中[UINib loadCachedForKey:]是我的类别,哪个实现就像方法名称一样简单,所以我觉得在这里发布它是没用的。

我也有类似的xib但是使用UIPicker并且它被快速实例化(~70ms)。 以编程方式添加日期选择器对我有用,但问题
我做错了什么这是正常的行为吗?

1 个答案:

答案 0 :(得分:0)

最好不要在此使用xib文件,在添加日期选择器时以编程方式使用:如果它对您有用,请尝试此操作:

- (IBAction)btnClicked:(id)sender {
    UIDatePicker *datepicker=[[UIDatePicker alloc] initWithFrame:CGRectMake(0, 250, 325, 300)];
    datepicker.datePickerMode = UIDatePickerModeDate;
    datepicker.hidden = NO;
    datepicker.date = [NSDate date];

    [datepicker addTarget:self
                   action:@selector(LabelChange:)
         forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:datepicker]; //this can set value of selected date to your label change according to your condition


    NSDateFormatter * df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"M-d-yyyy"]; // from here u can change format..
    _selectedDate.text=[df stringFromDate:datepicker.date];
}
- (void)LabelChange:(id)sender{
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"M-d-yyyy"];
    _selectedDate.text = [NSString stringWithFormat:@"%@",
                          [df stringFromDate:datepicker.date]];
}
相关问题