UIPickerView动态填充外部XML文件中的数据

时间:2012-08-27 18:56:23

标签: iphone xcode uipickerview

是否可以从外部XML文件动态填充UIPickerView数据。 例如,我将在我的选择器视图中使用TextA,TextB和TextC,并且在远程服务器的XML文件中也有相同的内容。我已成功开发从远程服务器读取XML数据并在我的tableview中显示文本(它们是标题和URL)。但现在我正在尝试从我的XML文件中填充我的UIPickerView数据。这样做的主要目的是从我的XML文件中动态控制UIPickerView数据。 无论如何要做到这一点?

2 个答案:

答案 0 :(得分:1)

您可以使用NSXMLParser解析XMl文件。它是一个事件驱动的解析器,因此您必须设置一个委托来处理所有回调并从解析的节点创建数组和字典。

您还可以使用XMLReader之类的课程。这允许您简单地将xml作为NSData或NSString对象传递,并获得解析的NSDictionary。然后,您可以使用它来填充UIPickerView。

虽然它有点不方便,如果可以的话,使用.plist文件是更好的选择。当然,如果你想从其他平台访问相同的信息,这不是一个选择。

然后,下载文件后你所要做的就是:

NSArray *onlineList = [plistAsString propertyList];

或者如果您将文件下载到磁盘上:

NSArray *onlineList = [[NSArray alloc] initWithContentsOfFile:pathToPlistFile];
// release if not using ARC.

答案 1 :(得分:0)

我已完成以下操作以在我的某个应用中显示标题和网址。我想要填充选择器数据而不是表格单元格: This is a link of one of my apps演示了以下代码的实现:

urlString = @"http://jeewanaryal.web44.net/iPhoneXML/nepaliMoviesNews.xml";
data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
dict = [XMLReader dictionaryForXMLData:data error:nil];

newsItems = [[NSMutableArray alloc] initWithArray:[[[dict objectForKey:@"list"] objectForKey:@"lists"] objectForKey:@"news"]];



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

CustomCell *cell= [[CustomCell alloc] initWithFrame:CGRectMake(0, 0, 300, 60)];

// Default to no selected style and not selected
cell.selectionStyle = UITableViewCellSelectionStyleNone;

// Set the image for the cell  
[cell setTheImage:[UIImage imageNamed:[NSString stringWithFormat:@"Arrow3.png"]]];

NSMutableArray *temp = [[NSMutableArray alloc] init];

for (NSDictionary *fruitDict in newsItems) {


    //UILabel *songTitle = [[UILabel alloc] initWithFrame:CGRectMake(40, 200, 300, 40)];

    [temp insertObject:[NSString stringWithFormat:@"%@",[[fruitDict objectForKey:@"title"] objectForKey:@"text"]]
               atIndex:0];
    //cell.textLabel.text = [NSString stringWithFormat:@"%@",[[fruitDict objectForKey:@"title"] objectForKey:@"text"]];


    //[self.view addSubview:songTitle];
}

//NSLog(@"\n\n temp: \n %@",temp);

cell.textLabel.text = [temp objectAtIndex:indexPath.row];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.textLabel.font = [UIFont fontWithName:@"Gill Sans" size:20];
cell.textLabel.textColor = [UIColor colorWithRed:102.0/255 green:204.0/255 blue:170.0/255 alpha:1];
//cell.textLabel.textColor =[UIColor colorWithRed:(CGFloat)0.24 green:(CGFloat)0.7 blue:(CGFloat)0.45 alpha:(CGFloat)1];
cell.backgroundColor = [UIColor blackColor];
[[cell textLabel] setTextAlignment:UITextAlignmentLeft];
//cell.textLabel.adjustsFontSizeToFitWidth = YES;
//cell.detailTextLabel.numberOfLines = 2;  

return cell;
}
相关问题