我一直无法从textfield的inputview属性中提取自定义UIPickerView。我已经研究了一段时间,做了一些研究,并尝试将基于Apple的UICatalog示例的单独项目组合在一起。
然而,每当我点击文本字段内部时,我得到的就是一个黑色屏幕,它会弹出取代选择器视图。我确定我已经忽略了一些东西,但我一直在寻找任何帮助将会受到赞赏。
请记住,这是我的测试项目,看看我是否可以将此功能添加到我的其他应用程序以及我尝试从UICatalog应用程序复制的许多代码。对不起,如果没有任何意义,请随时提出任何问题。谢谢。
// ViewController.h
// TestPicker
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController<UITextFieldDelegate,UIPickerViewDelegate,UIPickerViewDataSource>{
UIPickerView *picker;
//The picker view the textfield responds to.
IBOutlet UITextField *myText;
//The textfield which has the input view of a picker.
NSArray *testArray;
//The array which values are loaded into the picker.
}
@end
// ViewController.m
// TestPicker
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
picker.delegate=self;
picker.dataSource=self;
myText.delegate=self;
[self createPicker];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)viewDidUnload
{
myText = nil;
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
else {
return YES;
}
}
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
picker = [[UIPickerView alloc] initWithFrame:CGRectZero];
myText.inputView=picker;
return YES;
}
-(void)textFieldDidBeginEditing:(UITextField *)textField{
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
NSString *returnStr = @"";
if (pickerView == picker)
{
if (component == 0)
{
returnStr = [testArray objectAtIndex:row];
}
else
{
returnStr = [[NSNumber numberWithInt:row] stringValue];
}
}
return returnStr;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return [testArray count];
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
- (void)createPicker
{
testArray = [NSArray arrayWithObjects:
@"John Appleseed", @"Chris Armstrong", @"Serena Auroux",
@"Susan Bean", @"Luis Becerra", @"Kate Bell", @"Alain Briere",
nil];
picker = [[UIPickerView alloc] initWithFrame:CGRectZero];
picker.showsSelectionIndicator = YES; // note this is default to NO
picker.delegate = self;
picker.dataSource = self;
}
@end
答案 0 :(得分:3)
问题出在这个方法中:
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
picker = [[UIPickerView alloc] initWithFrame:CGRectZero];
myText.inputView=picker;
return YES;
}
您已经在createPicker方法中创建了picker,从viewDidLoad调用,因此这会创建另一个实例(此实例不会将委托或数据源设置为self,因为这些是在您创建的第一个实例上设置的)。如果您只是删除此方法的第一行,它应该可以工作。
对您的代码另外两条评论。 viewDidLoad方法中的前两行没有做任何事情,因为你还没有创建选择器 - 它们应该被删除。您还需要实现pickerView:didSelectRow:inComponent:方法,以便将选择器的选定值放入文本字段中。