UIPickerview 多个 TextFields Xcode

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12812510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 01:45:47  来源:igfitidea点击:

UIPickerview Multiple TextFields Xcode

iphoneobjective-cxcodeuipickerview

提问by Shaun Wright

I'm looking for a way to use a single UIPickerview for two different textfields. I'd like to have the pickerview popup when each textfield is selected. After the user selects their item, the item will populate the specific text field. The picker would have to populate based on the textfield chosen.

我正在寻找一种对两个不同的文本字段使用单个 UIPickerview 的方法。我希望在选择每个文本字段时弹出选择器视图。用户选择他们的项目后,该项目将填充特定的文本字段。选择器必须根据所选的文本字段进行填充。

I've read this:

How to use one UIPickerView for multiple textfields in one view?

and this:

How to use UIPickerView to populate different textfields in one view?

and this:

Multiple sources for UIPickerView on textfield editing

我读过这篇文章:

如何在一个视图中为多个文本字段使用一个 UIPickerView?

和这个:

如何使用 UIPickerView 在一个视图中填充不同的文本字段?

和这个:

UIPickerView 文本字段编辑的多个来源

However, none gives a complete solution.

然而,没有一个给出完整的解决方案。

I'm very new at Xcode so I'd like a solution that includes steps to set the storyboard also.

我对 Xcode 很陌生,所以我想要一个解决方案,其中包括设置故事板的步骤。

I appreciate any help as i've researched this for weeks.

感谢您的帮助,因为我已经研究了数周。

EDIT: HERE IS MY CODE:

编辑:这是我的代码:

.h:
#import <UIKit/UIKit.h>

@interface klViewController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource> {

IBOutlet UITextField *textField1;
IBOutlet UITextField *textField2;
NSMutableArray *pickerArray1;
NSMutableArray *pickerArray2;
UIPickerView *pickerView;
}
@property(nonatomic,retain) IBOutlet UITextField *textField1;
@property(nonatomic,retain) IBOutlet UITextField *textField2;
@property(nonatomic,retain) IBOutlet UIPickerView *pickerView;


@end

.m:
#import "klViewController.h"

@interface klViewController ()

@end

@implementation klViewController
@synthesize pickerView;
@synthesize textField1;
@synthesize textField2;
int variabla;

-(void)textFieldDidBeginEditing:(UITextField *)textField{
    [pickerView setHidden:YES];
    if (textField1.editing == YES) {
        [textField1 resignFirstResponder];
        [pickerView setHidden:NO];
        variabla = 1;
    }else if (textField2.editing == YES) {
        [textField2 resignFirstResponder];
        [pickerView setHidden:NO];
        variabla = 2;
    }
    NSLog(@"variabla %d",variabla);
    [pickerView reloadAllComponents];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView;
{
    return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component;
{
    if (variabla == 1) {
        return [pickerArray1 count];
    }else if (variabla == 2) {
        return [pickerArray2 count];
    }else {
        return 0;
    }
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component;
{
    if (variabla == 1) {
        return [pickerArray1 objectAtIndex:row];
    }else if (variabla == 2) {
        return [pickerArray2 objectAtIndex:row];
    }else {
        return 0;
    }
}
- (void)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [pickerView setHidden:YES];
    pickerArray1 = [[NSMutableArray alloc] initWithObjects:@"0", @"1", @"2", nil];
    pickerArray2 = [[NSMutableArray alloc] initWithObjects:@"3", @"4", @"5", nil];
}

@end

HERE IS A SCREEN SHOT OF MY STORYBOARD:

这是我的故事板的屏幕截图:

Screen Shot of my StoryBoard

我的故事板的屏幕截图

STATUS UPDATE:

状态更新:

When I run the program:
1) the pickerview is hidden.
2) when I select a textfield, the picker view appears and populates correctly depending on the textfield selected.

当我运行程序时:
1)选择器视图被隐藏。
2)当我选择一个文本字段时,选择器视图会出现并根据所选的文本字段正确填充。

PROBLEMS:
1) Picker doesn't go away when click outside of the textfield.
2) Textfields don't populated when a row in the Picker is selected.

问题:
1) 在文本字段外单击时,选择器不会消失。
2) Textfields don't populated when a row in the Picker is selected.

Hope this provides more insight.

希望这能提供更多的见解。

采纳答案by NJones

1) Picker doesn't go away when click outside of the textfield.

1) 在文本字段外单击时,选择器不会消失。

You have no code that attempts to make the picker go away when that happens. Try adding a simple tap gesture recognizer to the view. Add a line to viewDidLoadlike:

当发生这种情况时,您没有尝试使选择器消失的代码。尝试在视图中添加一个简单的点击手势识别器。添加一行viewDidLoad喜欢:

[self.view addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backgroundTap:)]];

Then implement the function simply like:

然后简单地实现这个功能:

-(void)backgroundTap:(UITapGestureRecognizer *)tapGR{
    self.pickerView.hidden = YES;
    // And maybe..
    variabla = 0;
}

Since you are making the picker appear and disappear using the hidden property this will work very simply. There are other more sophisticated ways to do this which I hope you explore. Generally the picker is set as the textfield's inputViewproperty; that is worth investigating.

由于您使用 hidden 属性使选择器出现和消失,这将非常简单地工作。还有其他更复杂的方法可以做到这一点,我希望你能探索一下。通常选择器被设置为文本字段的inputView属性;这是值得研究的。

2) Textfields don't populated when a row in the Picker is selected.

2) Textfields don't populated when a row in the Picker is selected.

You haven't handled the picker's pickerView:didSelectRow:inComponent:delegate method. That's the method that gets called when the picker stops turning and lands on an item. Don't assume that this is the item the user selected it will be called multiple times.

您还没有处理过选择器的pickerView:didSelectRow:inComponent:委托方法。That's the method that gets called when the picker stops turning and lands on an item. 不要假设这是用户选择的项目,它将被多次调用。

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    NSString *text = [self pickerView:pickerView titleForRow:row forComponent:component];
    UITextField *current = nil;
    if (variabla == 1) current = self.textField1;
    else if (variabla == 2) current = self.textField2;
    current.text = text;
}

That should get your implementation working. One more thing though variablais an instance variable and should be declared in curly braces immediately following the @interfaceor @implementationline.

这应该让你的实现工作。还有一件事variabla是一个实例变量,应该在紧跟在@interfaceor@implementation行之后的花括号中声明。

@implementation klViewController {
    int variabla;
}
@synt....

回答by Rushang Prajapati

Give the Tag of two Different textfield for identify which textfield you select and everything is ok you just need to change below method. Hope This Work

给出两个不同文本字段的标签,以识别您选择的文本字段,一切正常,您只需要更改以下方法即可。希望这项工作

-(void)textFieldDidBeginEditing:(UITextField *)textField  {




if ([textField viewWithTag:100]) {

    [textField resignFirstResponder];
    [self.View1 setHidden:NO];
    variable=1;
}

else if ([textField viewWithTag:101]) {

否则 if ([textField viewWithTag:101]) {

    [textField resignFirstResponder];
    [self.View1 setHidden:NO];
     variable=2;

}

    [_Picker_view reloadAllComponents];

}

}

Thanks :)

谢谢 :)

回答by Venk

In .h

在.h

@interface TQViewController : UIViewController<UIPickerViewDelegate>
{
    UITextField *textfield;
    UIPickerView *Picker1;
    NSArray *Array1,*Array2;
}
end

and in .m

并在.m

    - (void)viewDidLoad
    {

        [super viewDidLoad];

        //TextField
        textfield=[[UITextField alloc]initWithFrame:CGRectMake(5,5,310,40)];
        textfield.borderStyle = UITextBorderStyleRoundedRect;
        textfield.backgroundColor=[UIColor whiteColor];
        textfield.textAlignment = UITextAlignmentCenter;
        textfield.placeholder = @"<enter amount>";
        [self.view addSubview:textfield];
textfield1=[[UITextField alloc]initWithFrame:CGRectMake(5,100,310,40)];
        textfield1.borderStyle = UITextBorderStyleRoundedRect;
        textfield1.backgroundColor=[UIColor whiteColor];
        textfield1.textAlignment = UITextAlignmentCenter;
        textfield1.placeholder = @"<enter amount>";
        [self.view addSubview:textfield1];

        // PickerView1
        Array1=[[NSArray alloc]initWithObjects:@"USD",@"INR",@"EUR", nil];
        Picker1=[[UIPickerView alloc]initWithFrame:CGRectMake(0, 50, 320,10)];
        Picker1.delegate=self;
        Picker1.tag=PICKER1_TAG;
        Picker1.showsSelectionIndicator=YES;
        [self.view addSubview:Picker1];
     Array2=[[NSArray alloc]initWithObjects:@"USD",@"INR",@"EUR", nil];
    }
       -(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
        {
           if([textfield becomeFirstResponder])
            return [Array1 count];
           if([textfield1 becomeFirstResponder])
            return [Array2 count];
        }
        - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
          NSString *title;
            if([textfield becomeFirstResponder])
            {
                title=[Array1 objectAtIndex:row];  
                return title; 
            }
            ([textfield1 becomeFirstResponder])
            {
                title=[Array2 objectAtIndex:row];  
                return title; 

            }       
        }

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

if([textfield becomeFirstResponder])
            {
                //your code 
            }
            ([textfield1 becomeFirstResponder])
            {
                //your code  

            } 
}

回答by Shachar

  1. Make sure you have declared the Picker View object in the header file.
  2. In the header file, import the UITextFieldDelegate protocol:

    @interface MyView:UIViewController < UITextFieldDelegate>

  3. In IB, set a tag for each text field you have.

  4. In the *.m file, implement the textFieldShouldBeginEditing method, update the PickerView array Data Source and Reload all the picker view components.

       -(BOOL) textFieldShouldBeginEditing:(UITextField *)textField {
    
       if (textField.tag == 1) {
    
       itemsArray = [[NSArray alloc] arrayWithObjects:@"A", @"B"];
    
       }
    
       if (textField.tag == 2) {
    
           itemsArray = [[NSArray alloc] arrayWithObjects:@"Green", @"Yellow"];
       }
    
       [myPickerView reloadAllComponents];
       }
    
  5. Make sure you import the UIPickerViewDelegate and UIPickerViewDataSource in the header file.

  1. 确保您已经在头文件中声明了 Picker View 对象。
  2. 在头文件中,导入 UITextFieldDelegate 协议:

    @interface MyView:UIViewController < UITextFieldDelegate>

  3. 在 IB 中,为您拥有的每个文本字段设置一个标签。

  4. 在 *.m 文件中,实现 textFieldShouldBeginEditing 方法,更新 PickerView 数组数据源并重新加载所有选择器视图组件。

       -(BOOL) textFieldShouldBeginEditing:(UITextField *)textField {
    
       if (textField.tag == 1) {
    
       itemsArray = [[NSArray alloc] arrayWithObjects:@"A", @"B"];
    
       }
    
       if (textField.tag == 2) {
    
           itemsArray = [[NSArray alloc] arrayWithObjects:@"Green", @"Yellow"];
       }
    
       [myPickerView reloadAllComponents];
       }
    
  5. 确保在头文件中导入 UIPickerViewDelegate 和 UIPickerViewDataSource 。

You can use the same picker view for as many text fields as you want, to change the content of the picker view according to the selected text field you need to replace the data source of the picker view with different items whenever a text field is being selected and then reload the picker view components.

您可以根据需要对任意数量的文本字段使用相同的选择器视图,要根据选定的文本字段更改选择器视图的内容,您需要在文本字段出现时将选择器视图的数据源替换为不同的项目选择,然后重新加载选择器视图组件。

Well my friend, I'm afraid it's a little bit to complicated to explain here. You can set object's tag value in the IB properties menu. Once you dragged a PickerView into your view and it's selected, you can change the tag attribute in the Object Properties menu (on the side). I think you should look for tutorials that will show you how to setup a simple picker view, or table view (they work very similar to one another) and that will give you much more information on how to do what you want to do. In a nutshell, every Picker View takes information from a Data Source, you can create an array that contains some strings and have the picker view load each item in the array as a row. I have a small website with some beginners information, check it out.
http://i-tutor.weebly.com/index.html

好吧,我的朋友,恐怕在这里解释起来有点复杂。您可以在 IB 属性菜单中设置对象的标签值。一旦您将 PickerView 拖入您的视图并被选中,您就可以在“对象属性”菜单(在侧面)中更改标签属性。我认为您应该寻找一些教程,这些教程将向您展示如何设置一个简单的选择器视图或表格视图(它们的工作原理非常相似),这将为您提供有关如何做您想做的事情的更多信息。简而言之,每个选择器视图都从数据源获取信息,您可以创建一个包含一些字符串的数组,并让选择器视图将数组中的每个项目作为一行加载。我有一个包含一些初学者信息的小网站,请查看。
http://i-tutor.weebly.com/index.html