2012-08-27 155 views
0

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

+0

是否需要XML?使用.plist文件会更容易。 – DrummerB

+0

雅我可以使用.plist为此,但我想控制从我的外部网站pickerview内的数据,因为pickerview中的所有数据都是动态的,他们将来会改变。什么是最好的设计方法? – jeewan

回答

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; 
} 
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. 
+0

丢弃此... – jeewan