我正在練習使用選取器將值輸入到文本字段中。我試着調整一些在這裏找到的代碼,以便在文本框被觸摸時顯示一個選擇器來填寫文本字段。文本框內置代碼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
感謝的是,無論在哪裏我把這些代碼我剛剛得到的標準鍵盤呈現排序呢? – JSA986 2012-07-29 13:12:03