iPhone ComboBox
iPhone Safari 风格的 ComboBox

引言
我正在开发一个项目,需要将一个包含许多组合框的 Android 应用程序移植到原生 iPhone 应用程序。要求是保持移植应用程序的外观和感觉;不幸的是,iOS 不包含组合框控件。我提出的解决方案是使用 UIPickerView
作为输入而不是键盘的 UITextField
,类似于 Safari 实现 HTML select 字段的方式。
实现
我创建了一个 UIViewController
子类,其中包含一个 UITextField
和一个箭头图像,使其看起来像一个组合框。
当用户触摸 UITextField
时,将调用以下操作
- (IBAction)showPicker:(id)sender
{
pickerView = [[UIPickerView alloc] init];
pickerView.showsSelectionIndicator = YES;
pickerView.dataSource = self;
pickerView.delegate = self;
UIToolbar* toolbar = [[UIToolbar alloc] init];
toolbar.barStyle = UIBarStyleBlackTranslucent;
[toolbar sizeToFit];
//to make the done button aligned to the right
UIBarButtonItem *flexibleSpaceLeft = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem* doneButton = [[UIBarButtonItem alloc] initWithTitle:@"Done"
style:UIBarButtonItemStyleDone target:self
action:@selector(doneClicked:)];
[toolbar setItems:[NSArray arrayWithObjects:flexibleSpaceLeft, doneButton, nil]];
//custom input view
textField.inputView = pickerView;
textField.inputAccessoryView = toolbar;
}
-(void)doneClicked:(id)sender
{
[textField resignFirstResponder]; //hides the pickerView
}
附带的源代码
- iPhoneComboBox_src.zip 包含子类化的
ControllerView
,以便轻松集成到现有项目中。 - iPhoneComboBox_demo.zip 包含使用
ComboBox ControllerView
的演示应用程序的源代码。
Using the Code
- 打开 Xcode 并创建一个“Single View Application”,将其命名为
ComboBoxTest
。
确保选中“Use Automatic Reference Counting”。 - 下载并解压缩 iPhoneComboBox_src.zip 到一个名为 ComboBox 的文件夹(双击 zip 文件)。
- 将 ComboBox 文件夹拖放到 Xcode 中的项目中。
确保选中“Copy items into destination group’s folder”。
确保选中“Create groups for any added folders”。 - 编辑 ViewController.h:添加
#import "ComboBox.h"
,声明ComboBox* combo1;
头文件应如下所示#import <uikit> #import "ComboBox.h" @interface ViewController : UIViewController { ComboBox* combo1; } @end
- 编辑 ViewController.m,将以下内容添加到
viewDidLoad
NSMutableArray* fruitsArray = [[NSMutableArray alloc] init]; [fruitsArray addObject:@"Apple"]; [fruitsArray addObject:@"Banana"]; [fruitsArray addObject:@"Orange"]; combo1 = [[ComboBox alloc] init]; [combo1 setComboData:fruitsArray]; //Assign the array to ComboBox [self.view addSubview:combo1.view]; combo1.view.frame = CGRectMake(110, 69, 120, 31); //ComboBox location and //size (x,y,width,height)
- 构建并运行,就完成了。
历史
- 2011年12月17日:初始发布