如何在单击UI按钮时显示UIPickerVIew

时间:2012-12-04 08:42:05

标签: ios uiscrollview

我有一个UIScrollView,其中有几个UIViews作为子视图。其中一个UIView我需要创建一个UIButton,点击其中一个UIPickerView应该出现,如果我可以让按钮成为第一个响应者,那么通过默认操作UIScrollView,它会向上滚动以便为UIPickerView建立...有什么方法可以实现这一目标吗?我需要继承UIControl吗?

3 个答案:

答案 0 :(得分:2)

您可以使用:

-(void)btnAction{
UITextView* uitextView = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, 1, 1)];
uitextView.inputView = thePickerView;
[self.view addSubview:uitextView];

[uitextView becomeFirstResponder];}

答案 1 :(得分:1)

这是按钮添加,在这种情况下直接在_scrollView中,您可以轻松更改。

UIButton *btn = [[UIButton alloc] init];

// button customization

[btn addTarget:self action:@selector(showPickerView:) forControlEvents:UIControlEventTouchUpInside];

[_scrollView addSubview:btn];
[btn release]; // if non-ARC

之后,您需要实现showPickerView:方法

- (void)showPickerView:(UIButton*)sender
{
    UIPickerView *picker = [[UIPickerView alloc] init];
    picker.tag = 998998;

    // picker customization..

    [self.view insertSubview:picker aboveSubview:_scrollView];
    [picker release]; // if non-ARC
}

这里重要的部分是当从选择器视图触发关闭/完成按钮时,您必须隐藏选择器,这是我想到的最简单的方法

if([self.view viewWithTag:998998] != nil) {
    [[self.view viewWithTag:998998] removeFromSuperview]
}

答案 2 :(得分:0)

将UIPickerView初始化为cell.picker = [[UIPickerView alloc] initWithFrame:CGRectZero];在一个子类中(以及任何你想要点击时出现的选择器)。然后遍历该类的inputView方法并返回该方法中的UIPickerView。该方法设置自定义输入视图,以便在对象成为第一个响应者时显示。它会像键盘一样为你制作动画。要使滚动视图向上滚动,您需要以与键盘相同的方式处理此操作(通过为scrollView设置contentOffset)。你可以在这里找到:apple documentation link。从这里开始它应该是相当直接的,因为你有通知当对象作为第一响应者并成为第一响应者时。只需使用那些键盘通知的通知,并使用默认的UIPickerView大小而不是键盘。

    - (void)initalizeInputView {
    self.picker = [[UIPickerView alloc] initWithFrame:CGRectZero];
    self.picker.showsSelectionIndicator = YES;
    self.picker.autoresizingMask = UIViewAutoresizingFlexibleHeight;
}


- (UIView *)inputView {
        return self.picker;
}