我是iOS開發新手(現在已經2周了),我正在開發一個iOS應用程序,我想用一個國家列表填寫一個UIPickerView
。IOS&Objective C - 如何用一系列國家填充UIPickerView?
以下是我迄今所做的:
1-創建的選擇器視圖
2-定義我的視圖控制器作爲代表到選擇器視圖
3-添加這些行的代碼,我的.m視圖控制器文件:(方法:viewDidLoad中,numberOfComponentsInPickerView,titleForRow)
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
NSMutableArray *countries = [NSMutableArray arrayWithCapacity: [[NSLocale ISOCountryCodes] count]];
for (NSString *countryCode in [NSLocale ISOCountryCodes])
{
NSString *identifier = [NSLocale localeIdentifierFromComponents: [NSDictionary dictionaryWithObject: countryCode forKey: NSLocaleCountryCode]];
NSString *country = [[NSLocale currentLocale] displayNameForKey: NSLocaleIdentifier value: identifier];
[countries addObject: country];
}
NSArray *sortedCountries = [countries sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return 1;// or the number of vertical "columns" the picker will show...
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
if (sortedCountries!=nil) {
return [sortedCountries count];//this will tell the picker how many rows it has - in this case, the size of your loaded array...
}
return 0;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
//you can also write code here to descide what data to return depending on the component ("column")
if (sortedCountries!=nil) {
return [sortedCountries objectAtIndex:row];//assuming the array contains strings..
}
else
{
NSLog(@"Register tab empty?");
}
return @"empty";//or nil, depending how protective you are
}
這裏是我的.h文件:
#import <UIKit/UIKit.h>
@interface RegisterViewController_iPhone : UIViewController <UIPickerViewDelegate> {
NSArray * sortedCountries;
}
@property (strong, nonatomic) IBOutlet UIPickerView *pickerView;
@end
當我跑步時,它給了我一個空的UIpickerView
,謝謝你的幫助,謝謝。
也許'sortedCountries'在這一點上是零?只需調試它並檢查或移動排序到'init',看看它是否工作。 – Artrmz
在viewDidLoad中將'NSArray * sortedCountries'更改爲'sortedCountries'。 –
@artrmz我在我的viewdidload中做了一個NSLOG,它不是空的 – samouray