如何在水平分页滚动视图中添加日期选择器?

时间:2015-01-23 05:35:01

标签: ios objective-c iphone cocoa ios5

我已经使用Paging创建了UIScrollview,但我想在某些页面中添加日期选择器。但是日期选择器滚动不起作用。

NSArray *colors = [NSArray arrayWithObjects:[UIColor redColor], [UIColor greenColor], [UIColor blueColor], nil];
for (int i = 0; i < colors.count; i++) {
    CGRect frame;
    frame.origin.x = self.scrollView.frame.size.width * i;
    frame.origin.y = 0;
    frame.size = self.scrollView.frame.size;

    UIView *subview = [[UIView alloc] initWithFrame:frame];
    subview.backgroundColor = [colors objectAtIndex:i];
    CGRect pickerFrame = CGRectMake(0,100,100,100);

    UIDatePicker *myPicker = [[UIDatePicker alloc] initWithFrame:pickerFrame];
    [myPicker addTarget:self action:@selector(pickerChanged:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:myPicker];
    [myPicker release];
    [self.scrollView addSubview:subview];
    [subview release];
}

self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * colors.count, self.scrollView.frame.size.height);

self.pageControl.currentPage = 0;
self.pageControl.numberOfPages = colors.count;

1 个答案:

答案 0 :(得分:1)

不是将选择器视图添加到self.view,而是将其添加到self.scrollView

[self.scrollView addSubview:myPicker];

或者,您可以将选择器视图作为输入视图添加到文本字段

for (int i = 0; i < colors.count; i++) {
    CGRect frame;
    frame.origin.x = self.scrollView.frame.size.width * i;
    frame.origin.y = 0;
    frame.size = self.scrollView.frame.size;

    UIView *subview = [[UIView alloc] initWithFrame:frame];
    subview.backgroundColor = [colors objectAtIndex:i];
    //CGRect pickerFrame = CGRectMake(0,100,100,100);

    myTextField = [[UITextField alloc]initWithFrame:
                                CGRectMake(10, 100, 300, 30)]; //if you dont want to show the text field you can change the frame to CGRectMake(0, 0, 1, 1)
    myTextField.borderStyle = UITextBorderStyleRoundedRect;
    myTextField.textAlignment = NSTextAlignmentCenter;
    myTextField.delegate = self;
    [self.view addSubview:myTextField];

    UIDatePicker *myPicker = [[UIDatePicker alloc] initWithFrame:pickerFrame];
    [myPicker addTarget:self action:@selector(pickerChanged:) forControlEvents:UIControlEventValueChanged];
    [myTextField setInputView:myPicker];
    [self.scrollView addSubview:myTextField];


    [myPicker release];

    [self.scrollView addSubview:subview];
    [subview release];
}

当您想要显示选择器时,请调用以下方法[self showPickerView]

- (void)showPickerView
{
    [myTextField becomeFirstResponder];
}