ピッカーを使用してテキスト フィールドに値を入力する練習をしています。テキストボックスに触れてテキストフィールドに入力するときにピッカーを表示するために、ここにあるコードをいくつか適応させようとしました。テキスト ボックスはコードSOURCEに組み込まれており、IB でテキスト ボックスを構築したいと考えています。ただし、これによりプレゼンテーション ピッカー ビューが停止し、代わりにキーボードのみが表示されるようになりました
おそらく、誰かがここで私を正しい方向に向けるでしょう. 私のコード:
.h
#import <UIKit/UIKit.h>
@interface pick2 : UIViewController
<UIPickerViewDelegate, UIPickerViewDataSource> {
UIPickerView *locationsPicker;
UIToolbar *accessoryView;
UITextField *text1;
NSArray *locations;
}
@property (nonatomic, readonly) UIPickerView *locationsPicker;
@property (nonatomic, readonly) UIToolbar *accessoryView;
@property (strong, nonatomic) IBOutlet UITextField *text1;
- (void)onLocationSelection;
@end
.m
#import "pick2.h"
@interface pick2 ()
@end
@implementation pick2
@synthesize text1;
- (UIPickerView *)locationsPicker {
if ( locationsPicker == nil ) {
locationsPicker = [[UIPickerView alloc] init];
locationsPicker.delegate = self;
locationsPicker.dataSource = self;
locationsPicker.showsSelectionIndicator = YES;
}
return locationsPicker;
}
- (UIToolbar *)accessoryView {
if ( accessoryView == nil ) {
accessoryView = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonItemStylePlain
target:self
action:@selector(onLocationSelection)];
[accessoryView setItems:[NSArray arrayWithObject:doneButton]];
}
return accessoryView;
}
#pragma mark - Memory management
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (void)onLocationSelection {
NSInteger row = [self.locationsPicker selectedRowInComponent:0];
( [text1 isFirstResponder] ); {
text1.text = [locations objectAtIndex:row];
[text1 resignFirstResponder];
}
}
- (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - picker view delegate/datasource
- (NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
return [locations objectAtIndex:row];
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent: (NSInteger)component {
return [locations count];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
locations = [[NSArray alloc] initWithObjects:@"New York", @"Chicago", @"Memphis", @"California", @"Seattle",@"London",@"Paris", nil];
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)viewDidUnload
{
[self setText1:nil];
[super viewDidUnload];
}
@end