繁体   English   中英

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

[英]How to show a UIPickerVIew on click of a UIbutton

我有一个UIScrollView ,其中我有几个UIViews作为子视图。 在其中一个UIView我需要创建一个UIButton ,点击其中, UIPickerView应该出现,如果我可以使按钮成为第一个响应者然后通过UIScrollView的默认操作,它将向上滚动以为UIPickerView创建位置......有什么方法可以做到这一点吗? 我需要UIControl吗?

你可以用这个:

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

[uitextView becomeFirstResponder];}

这是按钮添加,在这种情况下直接在_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]
}

将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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM