【发布时间】:2015-10-21 20:09:32
【问题描述】:
我正在尝试以编程方式添加UIPickerView,但没有得到想要的结果。
我有一个滚动视图,其中添加了一些UITextFields,如下图所示。
这个想法是,当用户选择DATE 时,会显示UIDatePicker 并且用户选择DATE。按下DATE 选择器UIBarButtonItem(我也以编程方式添加)上的NEXT 按钮,TIME 文本字段获得焦点,并显示UIDatePicker(默认为时间)。对于DATE 和TIME 字段,我使用了UIDatePicker,这是100% 的工作。
对于剩下的 3 个文本字段,我尝试做同样的事情,但改用 UIPickerView,因为它们的类型不是 DATE 或 TIME。
但是,当我运行我的代码时,我会得到如下结果,如下所示。可能很难从图像中辨认出来,但底部黄色 SEARCH 按钮的后面/上方应该是 UIPickerView(可以看作是在 PROFILE 和 SEARCH 条形项目上方的灰线)
我的 UIPickerViewDelegate 方法(numberOfComponentsInPickerView、numberOfRowsInComponent、titleForRow 和 didSelectRow)在视图首次出现时运行,但从执行程序时我可以看到的情况不再运行。在这里,我定义了要在 Country 或 County 文本字段中显示的数据数组。
下面是到目前为止我必须以编程方式显示UIPickerViews 的代码。
- (void)viewDidLoad
{
[super viewDidLoad];
[self initPickers];
}
- (void) initPickers
{
// Used for all other reusable UIPickerViews
pickerView = [[UIPickerView alloc] init];
}
然后当例如COUNTRY 文本字段获得焦点(这是经过测试和工作的),我为 UIPickerView 设置动画,如下所示:
- (BOOL) textFieldShouldBeginEditing:(UITextField*) textField
{
activeTextField = textField;
if (activeTextField.tag == 2)
{
self.countryTextField.inputView = pickerView;
// We are on the Country Text Field
currentArray = countryDataArray;
NSLog(@"Array Count %ld", [currentArray count]); // Is populated with data
[self animatePickerViewIn];
return NO;
}
return YES;
}
-(void) animatePickerViewIn
{
// Get the screen width and size
float screenWidth = [[UIScreen mainScreen] bounds].size.width;
float screenHeight = [[UIScreen mainScreen] bounds].size.height;
// Calculate the starting X Coordinate
float pickerWidth = screenWidth;
float pickerHeight = pickerView.frame.size.height;
float pickerViewStartinYCoordinate = screenHeight - pickerView.frame.size.height;
// Animate in and set PickerView to dimensions and coordinates
[UIView animateWithDuration:0.25 animations:^{
[pickerView setFrame:CGRectMake(0, pickerViewStartinYCoordinate, pickerWidth, pickerHeight)];
[self.view addSubview:pickerView];
}];
}
谁能解释一下为什么我没有看到完整的 UIPickerView?
【问题讨论】:
-
该动画是否应该像键盘动画一样对其进行动画处理?我认为它会自动为您执行此操作,只需像您一样将其设置为 inputView 即可。试着去掉动画,看看它是否有效
-
为什么需要尝试为选择器视图设置动画?
-
我尝试删除动画并仅在视图加载时显示选择器,但我仍然得到与问题相同的结果。这是我在没有动画的情况下测试它的方法: - (void) initPickers { pickerView = [[UIPickerView alloc] init]; float screenWidth = [[UIScreen mainScreen] bounds].size.width; float screenHeight = [[UIScreen mainScreen] bounds].size.height;浮动选择器宽度 = 屏幕宽度;浮动pickerHeight = pickerView.frame.size.height;浮动pickerViewStartinYCoordinate = screenHeight - pickerView.frame.size.height; [self.view addSubview:pickerView]; }
标签: ios iphone uitextfield uipickerview