隐藏/显示 UIPickerView

发布于 2024-08-28 23:36:07 字数 814 浏览 5 评论 0原文

我有一个 TouchsEnded 事件,用于检查何时按下 UITextField。我希望它做的是隐藏/显示 UIPickerView。这怎么能做到呢?

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [[event allTouches] anyObject];
    if (CGRectContainsPoint([self.textField frame], [touch locationInView:self.view]))
    {
        NSString * error = @"Touched the TextField";
        UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:@"Selection!" message:error delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [errorAlert show];
        //Want to show or hide UIPickerView
    }
}

当触摸发生时我已经分配了 UIPickerView

@interface ThirdViewController : UIViewController <UITextFieldDelegate,UIPickerViewDelegate> {
    IBOutlet UIPickerView *pickerView;
}

I Have an a touchesEnded event that checks for when a UITextField is pressed. What I would like it to do is is hide/show a UIPickerView. How can this be done?

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [[event allTouches] anyObject];
    if (CGRectContainsPoint([self.textField frame], [touch locationInView:self.view]))
    {
        NSString * error = @"Touched the TextField";
        UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:@"Selection!" message:error delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [errorAlert show];
        //Want to show or hide UIPickerView
    }
}

I already have an allocated UIPickerView when touches occur

@interface ThirdViewController : UIViewController <UITextFieldDelegate,UIPickerViewDelegate> {
    IBOutlet UIPickerView *pickerView;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

﹏雨一样淡蓝的深情 2024-09-04 23:36:07

切换“隐藏”属性可以解决问题,但也会带来非常突然的揭示。

避免这种情况的一种方法是将选择器嵌入 UIActionSheet 中,使其从屏幕底部向上滑动。

这是一个示例:

    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil 
delegate:nil cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];

    CGRect pickerFrame = CGRectMake(0, 0, 0, 0);
    UIPickerView *pickerView = [[UIPickerView alloc] initWithFrame:pickerFrame];
    pickerView.showsSelectionIndicator = YES;
    pickerView.dataSource = self;
    pickerView.delegate = self;
    [sheet addSubview:pickerView];
    [pickerView release];

    [sheet showInView:view];
    [sheet setBounds:CGRectMake(0, 0, 320, 415)];
    self.actionSheet = sheet; // assuming you have setup a property to hold the action sheet
    [sheet release];

当您完成选择器后,将其关闭:

[self.actionSheet dismissWithClickedButtonIndex:0 animated:YES];

此方法也可用于在选择器上方的栏中合并按钮(“完成”、“上一个”、“下一个”等) - 有一个很好的解释如何操作此处

Toggling the "hidden" property will do the trick, but will also give a very abrupt reveal.

One way to avoid this is to get the picker to slide up from the bottom of the screen by embedding it inside a UIActionSheet.

Here's an example:

    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil 
delegate:nil cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];

    CGRect pickerFrame = CGRectMake(0, 0, 0, 0);
    UIPickerView *pickerView = [[UIPickerView alloc] initWithFrame:pickerFrame];
    pickerView.showsSelectionIndicator = YES;
    pickerView.dataSource = self;
    pickerView.delegate = self;
    [sheet addSubview:pickerView];
    [pickerView release];

    [sheet showInView:view];
    [sheet setBounds:CGRectMake(0, 0, 320, 415)];
    self.actionSheet = sheet; // assuming you have setup a property to hold the action sheet
    [sheet release];

When you've finished with the picker, dismiss it:

[self.actionSheet dismissWithClickedButtonIndex:0 animated:YES];

This approach can also be used to incorporate buttons in a bar above the picker ("Done", "Previous", "Next" etc) - there's a good explanation of how to do it here.

冧九 2024-09-04 23:36:07

因为我看到了有关这些解决方案在 iOS 7 上不起作用的评论,所以我假设该线程仍然相关并且正在被搜索。

我发现做到这一点的最好方法是将 UIPickerView 附加到(隐藏)UITextField 作为输入视图,如下所示:

_myPicker = [[UIPickerView alloc] init];
_myPicker.delegate = self;
_myPicker.showsSelectionIndicator = YES;
myTextField.inputView = _myPicker;

如果需要,您可以随时隐藏文本字段。然后,您可以通过激活文本字段作为第一响应者来显示/隐藏 UIPickerView,例如:

[myTextField becomeFirstResponder];
[myTextField resignFirstResponder];

我已经验证了这在 iOS 7 上有效,而且早在 iOS 5 上我就已经让它工作了。

Because I saw a comment about these solutions not working on iOS 7 I will assume this thread is still relevant and being searched for.

The best way I have found to do this is by attaching the UIPickerView to a (hidden)UITextField as the input view like:

_myPicker = [[UIPickerView alloc] init];
_myPicker.delegate = self;
_myPicker.showsSelectionIndicator = YES;
myTextField.inputView = _myPicker;

You can always hide the text field if desired. Then you can show/hide the UIPickerView by activating the textfield as first responder like:

[myTextField becomeFirstResponder];
[myTextField resignFirstResponder];

I have verified this works on iOS 7 and I have had it working as far back as iOS 5.

罪#恶を代价 2024-09-04 23:36:07

UIPickerView 继承自 UIView,因此您应该能够切换其“隐藏”属性:

if (pickerView) pickerView.hidden = !pickerView.hidden;

UIPickerView inherits from UIView, so you should be able to just toggle its 'hidden' property:

if (pickerView) pickerView.hidden = !pickerView.hidden;
卸妝后依然美 2024-09-04 23:36:07

我使用虚拟 UITextField 来显示/隐藏 UIPickerView

首先,在 UIViewController 上添加一个 UITextField 作为 @property代码>. (可选)还添加 UIPickerView 其次

@property (strong, nonatomic) UITextField *dummyTextField;

,为 UITextField 分配一个 UIPickerView 作为 inputView。将您自己指定为 UIPickerViewdataSourcedelegateUITextField 需要作为子视图添加到 UIViewControllerview 上。

- (void)viewDidLoad {

    [super viewDidLoad];

    UIPickerView *picker = [[UIPickerView alloc] init];
    [picker setDataSource:self];
    [picker setDelegate:self];

    self.dummyTextField = [UITextField new];
    self.dummyTextField.inputView = picker;
    [self.dummyTextField setHidden:YES];
    [self.view addSubview:self.dummyTextField];
}

最后,添加一个机制来显示和隐藏 UIPickerView。由于我使用的是虚拟 UITextField,因此我决定添加一个名为“Filter”的 UIBarButtonItem 以及以下 IBAction

- (IBAction)tappedFilterButton:(UIBarButtonItem *)sender {

    if (self.dummyTextField.isFirstResponder) {

        [self.dummyTextField resignFirstResponder];
    }
    else {

        [self.dummyTextField becomeFirstResponder];
    }
}

I am using a dummy UITextField for showing / hiding the UIPickerView

First, add a UITextField as a @property on your UIViewController. Optionally, add the UIPickerView, as well

@property (strong, nonatomic) UITextField *dummyTextField;

Second, assign a UIPickerView as inputView for the UITextField. Assign yourself as the dataSource and the delegate for the UIPickerView. UITextField needs to be added as a subview on your UIViewController's view.

- (void)viewDidLoad {

    [super viewDidLoad];

    UIPickerView *picker = [[UIPickerView alloc] init];
    [picker setDataSource:self];
    [picker setDelegate:self];

    self.dummyTextField = [UITextField new];
    self.dummyTextField.inputView = picker;
    [self.dummyTextField setHidden:YES];
    [self.view addSubview:self.dummyTextField];
}

Finally, add a mechanism to show and hide the UIPickerView. Since I am using a dummy UITextField, I have decided to add a UIBarButtonItem named "Filter" with the following IBAction:

- (IBAction)tappedFilterButton:(UIBarButtonItem *)sender {

    if (self.dummyTextField.isFirstResponder) {

        [self.dummyTextField resignFirstResponder];
    }
    else {

        [self.dummyTextField becomeFirstResponder];
    }
}
清旖 2024-09-04 23:36:07

因此,我使用了许多参考文献来试图解决这个问题,然后我最好的参考文献(信不信由你)来自苹果文档中的 UIView 类参考。

我在主视图之上构建了一个迷你视图(“_pickerView”),其中包含 UIToolBar、UIToolButton(带有 IBAction“closePicker”)和 UIPicker。

***请注意,这仅适用于 iOS 4.0 及更高版本

的代码关闭并显示 UIView (“_pickerView”)是:

-(IBAction)closePicker:(id)sender
{
    [UIView animateWithDuration:0.3 animations:^{ 
        _pickerView.frame = CGRectMake(_pickerView.frame.origin.x,
                                       460, //Displays the view off the screen
                                       _pickerView.frame.size.width,
                                       _pickerView.frame.size.height);
    }];
}

-(IBAction)showPicker:(id)sender
{
    [UIView animateWithDuration:0.3 animations:^{ 
        _pickerView.frame = CGRectMake(_pickerView.frame.origin.x,
                                       107, //Displays the view a little past the
                                            //center ling of the screen
                                       _pickerView.frame.size.width,
                                       _pickerView.frame.size.height);
    }];
}

对于您的 viewDidLoad 只需调用“closePicker”即可在加载时隐藏视图

So I have used many references on trying to figure this out and then my best reference (believe it or not), was from the apple docs on UIView Class reference.

I built a mini View ("_pickerView" on top of my main view that held a UIToolBar, UIToolButton (With IBAction "closePicker"), and the UIPicker.

***please note that is only works for iOS 4.0 and up

the code for closing and displaying the UIView ("_pickerView") is:

-(IBAction)closePicker:(id)sender
{
    [UIView animateWithDuration:0.3 animations:^{ 
        _pickerView.frame = CGRectMake(_pickerView.frame.origin.x,
                                       460, //Displays the view off the screen
                                       _pickerView.frame.size.width,
                                       _pickerView.frame.size.height);
    }];
}

-(IBAction)showPicker:(id)sender
{
    [UIView animateWithDuration:0.3 animations:^{ 
        _pickerView.frame = CGRectMake(_pickerView.frame.origin.x,
                                       107, //Displays the view a little past the
                                            //center ling of the screen
                                       _pickerView.frame.size.width,
                                       _pickerView.frame.size.height);
    }];
}

And for your viewDidLoad just call "closePicker" to have the view hidden on load

音盲 2024-09-04 23:36:07

在基于滚动视图的应用程序中,显示和隐藏 UIPickerView 可能是一个棘手的问题,因为将其固定到可见屏幕矩形的底部相对困难。您可以使用以下代码轻松完成。

let alertController = UIAlertController(title: title, message: "\n\n\n\n\n\n\n\n\n\n", preferredStyle: .ActionSheet)
alertController.view.addSubview(pickerView)
alertController.addAction(UIAlertAction(title: "OK", style: .Cancel) { action in
})
self.presentViewController(alertController, animated: true, completion: nil)

总而言之,您创建一个带有空消息的 UIAlertController。为了使alertController具有您的pickerView的大小,您需要为消息提供必要的换行符数量。最后,将 pickerView 添加为alertController.view 的子视图,

然后使用 UIPickerViewDelegate 方法跟踪选定的 pickerView 行。

In a scrollView based application, showing and hiding UIPickerView could be a tough issue as it is relatively hard to pin it to the bottom of the visible screen rectangle. You can do it easily with the following code.

let alertController = UIAlertController(title: title, message: "\n\n\n\n\n\n\n\n\n\n", preferredStyle: .ActionSheet)
alertController.view.addSubview(pickerView)
alertController.addAction(UIAlertAction(title: "OK", style: .Cancel) { action in
})
self.presentViewController(alertController, animated: true, completion: nil)

To summarize, you create an UIAlertController with an empty message. In order to make the alertController to have the size of your pickerView, you give the message neccessary number of line breaks. And lastly you add your pickerView as a subview of alertController.view

You then follow the selected pickerView rows with the UIPickerViewDelegate methods.

嗳卜坏 2024-09-04 23:36:07

我到处寻找一种使用单个按钮项目隐藏和显示(切换) UIPickerView 的干净方法,但只找到了零碎的东西。对于那些想要做同样事情的人,这是我通过基本条件语句得到的工作结果。

ViewController.m

- (IBAction)animatePicker {
    if ([self.userSelection.title isEqualToString: (NSString *)@"Select"]) {
        _userPicker.hidden = NO;
        UIPickerView *pickerView = [[UIPickerView alloc] init]; // default frame is set
        float pvHeight = pickerView.frame.size.height;
        float y = [[UIScreen mainScreen] bounds].size.height - (pvHeight); // the root view of view controller
        [UIView animateWithDuration:0.25f delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
            self.userPicker.frame = CGRectMake(0 , y, pickerView.frame.size.width, pvHeight);
        } completion:nil];
    } else if ([self.userSelection.title isEqualToString: (NSString *)@"Done"]) {
            UIPickerView *pickerView = [[UIPickerView alloc] init]; // default frame is set
            float pvHeight = pickerView.frame.size.height;
            float y = [[UIScreen mainScreen] bounds].size.height - (pvHeight * -2); // the root view of view controller
            [UIView animateWithDuration:0.25f delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
                self.userPicker.frame = CGRectMake(0 , y, pickerView.frame.size.width, pvHeight);
            } completion:nil];
        self.userSelection.title = @"Select";
        }
    }

这就是这里发生的事情:我有一个名为“userSelection”的按钮项,标题为“Select”,还有一个名为“userPicker”的隐藏 UIPickerView(要隐藏,只需复制关于“_userPicker.hidden”的一些信息,将其粘贴到选择器声明中,并将布尔值设置为 YES)。按钮项与上述操作相关。加载时(即当按钮的标题显示“选择”时),它会取消隐藏选择器并将其动画化到视图中。您可以使用 animateWithDuration 和延迟选项来控制该功能,但这些设置对我来说似乎很自然。

然后,当选择某些内容时,我可以使用此方法将按钮的标题更改为“完成”。我确信有一种更简洁的方法可以做到这一点,但是 switch 方法给了我一些自由,以防我以后想更改 UI。

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row   inComponent:(NSInteger)component{

    NSLog(@"Selected Row %ld", (long)row);
    switch(row)
    {

        case 0:
            self.userSelection.title = @"Done";
            break;
        case 1:
            self.userSelection.title = @"Done";
            break;
        case 2:
            self.userSelection.title = @"Done";
            break;
        case 3:
            self.userSelection.title = @"Done";
            break;
        case 4:
            self.userSelection.title = @"Done";
            break;
        case 5:
            self.userSelection.title = @"Done";
            break;
    }
}

最后,该操作以“else if”结束,当按钮显示“完成”时,使用反向动画隐藏选取器(相同的代码,但使用“pvHeight * -2”),然后将按钮的标题设置回“选择”用于完成整个动作的循环。

对于专业人士来说,这可能是一种更简单的方法,但对于像我这样刚接触这东西的人来说,这是最合乎逻辑的。而且它确实有效,所以这总是一个额外的好处!

I looked everywhere for a clean way to hide and show (toggle) UIPickerView using a single button item and only found bits and pieces. For those looking to do the same, here's my working result via a basic conditional statement.

ViewController.m

- (IBAction)animatePicker {
    if ([self.userSelection.title isEqualToString: (NSString *)@"Select"]) {
        _userPicker.hidden = NO;
        UIPickerView *pickerView = [[UIPickerView alloc] init]; // default frame is set
        float pvHeight = pickerView.frame.size.height;
        float y = [[UIScreen mainScreen] bounds].size.height - (pvHeight); // the root view of view controller
        [UIView animateWithDuration:0.25f delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
            self.userPicker.frame = CGRectMake(0 , y, pickerView.frame.size.width, pvHeight);
        } completion:nil];
    } else if ([self.userSelection.title isEqualToString: (NSString *)@"Done"]) {
            UIPickerView *pickerView = [[UIPickerView alloc] init]; // default frame is set
            float pvHeight = pickerView.frame.size.height;
            float y = [[UIScreen mainScreen] bounds].size.height - (pvHeight * -2); // the root view of view controller
            [UIView animateWithDuration:0.25f delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
                self.userPicker.frame = CGRectMake(0 , y, pickerView.frame.size.width, pvHeight);
            } completion:nil];
        self.userSelection.title = @"Select";
        }
    }

So here's what's going on here: I've got a button item called "userSelection" with a title of "Select" and a hidden UIPickerView called "userPicker" (to hide, just copy the bit about "_userPicker.hidden", paste it in your picker declaration, and set the boolean to YES). The button item is connected to the above action. On load (i.e. when the button's title says "Select"), it unhides the picker and animates it into view. You can use the animateWithDuration and delay options to control that function, but these settings seem pretty natural to me.

Then I've got this method changing the button's title to "Done" when something's been selected. I'm positive there's a cleaner way to do this bit, but the switch method gives me some freedom in case I want to make UI changes later.

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row   inComponent:(NSInteger)component{

    NSLog(@"Selected Row %ld", (long)row);
    switch(row)
    {

        case 0:
            self.userSelection.title = @"Done";
            break;
        case 1:
            self.userSelection.title = @"Done";
            break;
        case 2:
            self.userSelection.title = @"Done";
            break;
        case 3:
            self.userSelection.title = @"Done";
            break;
        case 4:
            self.userSelection.title = @"Done";
            break;
        case 5:
            self.userSelection.title = @"Done";
            break;
    }
}

Finally, the action closes with an "else if" that says when the button says "Done", hide the picker with the reverse animation (same code, but with "pvHeight * -2") and then sets the button's title back to "Select" which serves to complete the loop of the whole action.

Probably an easier way for the pros out there, but for the folks who are new to this stuff, like me, this made the most logical sense. Plus it works, so that's always a bonus!

蘑菇王子 2024-09-04 23:36:07

下面是 UIPickerView 带动画隐藏和显示的示例代码:-

//For Displaying

-(void)showPickerView{
    self.pickerSheet = [UIAlertController alertControllerWithTitle:@"Select font" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    self.pickerView = [[UIPickerView alloc]initWithFrame:CGRectZero];
    self.pickerView.dataSource = self;
    self.pickerView.delegate = self;
    self.pickerView.showsSelectionIndicator = YES;
    [self.pickerView selectRow:1 inComponent:0 animated:YES];
    [self.pickerSheet.view addSubview:self.pickerView];
    self.pickerView.translatesAutoresizingMaskIntoConstraints = NO;
    UIView *view = self.pickerView;
    [self.pickerSheet.view addConstraints:[NSLayoutConstraint
                               constraintsWithVisualFormat:@"V:|[view]|"
                               options:0l
                               metrics:nil
                               views:NSDictionaryOfVariableBindings(view)]];

    [self.pickerSheet.view addConstraints:[NSLayoutConstraint
                               constraintsWithVisualFormat:@"H:|[view]|"
                               options:0l
                               metrics:nil
                               views:NSDictionaryOfVariableBindings(view)]];
    [self presentViewController:self.pickerSheet animated:YES completion:^{
    }];

}

//For hide

-(void)hidePickerView{
    [self.pickerSheet dismissViewControllerAnimated:YES completion:^{
    }];
}

Below is the sample code to hide and show of UIPickerView with animation:-

//For Displaying

-(void)showPickerView{
    self.pickerSheet = [UIAlertController alertControllerWithTitle:@"Select font" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    self.pickerView = [[UIPickerView alloc]initWithFrame:CGRectZero];
    self.pickerView.dataSource = self;
    self.pickerView.delegate = self;
    self.pickerView.showsSelectionIndicator = YES;
    [self.pickerView selectRow:1 inComponent:0 animated:YES];
    [self.pickerSheet.view addSubview:self.pickerView];
    self.pickerView.translatesAutoresizingMaskIntoConstraints = NO;
    UIView *view = self.pickerView;
    [self.pickerSheet.view addConstraints:[NSLayoutConstraint
                               constraintsWithVisualFormat:@"V:|[view]|"
                               options:0l
                               metrics:nil
                               views:NSDictionaryOfVariableBindings(view)]];

    [self.pickerSheet.view addConstraints:[NSLayoutConstraint
                               constraintsWithVisualFormat:@"H:|[view]|"
                               options:0l
                               metrics:nil
                               views:NSDictionaryOfVariableBindings(view)]];
    [self presentViewController:self.pickerSheet animated:YES completion:^{
    }];

}

//For hiding

-(void)hidePickerView{
    [self.pickerSheet dismissViewControllerAnimated:YES completion:^{
    }];
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文