我一直在尝试使用这个 repo 的示例项目来试验在两个不同的 View Controller 之间传递数据:https://github.com/RajendrasinhParmar/DrawerMenu
我已经从 GitHub 下载了演示代码,我一直在尝试使用以下方法解析这个演示 JSON:
{
"menu": [
{
"name": "Facebook",
"url": "http://www.facebook.com"
},
{
"name": "Twitter",
"url": "http://www.twitter.com"
}
]
}
#pragma mark - http stuff
- (void)getMenuList {
NSError *error;
NSString *url_string = [NSString stringWithFormat: @"http://json-schema-faker.js.org/#gist/6a6cc18dc58dca786194f390c0af28c9"];
NSData *data = [NSData dataWithContentsOfURL: [NSURL URLWithString:url_string]];
NSMutableDictionary *response = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSMutableArray *menuArray = response[@"menu"];
// NSLog(@"response: %@", response);
for (int i=0; i < menuArray.count; i++) {
NSLog(@"%@", menuArray[i][@"name"]);
NSLog(@"%@", menuArray[i][@"url"]);
}
}
并在 MenuViewController 的 TableView 中显示“名称”,并在选择单元格时将 url 传递到 ViewController 的 Web View 。
我的问题是。如何在 Tableview 中分配名称属性并在选择时将 url 传递给 webview?我做了一些搜索,但我失败了。
最佳答案
首先,在 menuViewController 的界面中创建一个数组属性,并将 TableView 委托(delegate)和数据源添加到界面声明中。您还需要在界面生成器中向 menuViewController 添加一个 TableView ,并将其连接到您的 .h 文件。
@interface menuViewController:UIViewController <UITableViewDelegate, UITableViewDataSource>
@property(nonatomic) NSArray *menuArray;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@end
接下来,在获取 JSON 序列化后,分配给接口(interface)中定义的数组,然后重新加载 TableView
NSMutableDictionary *response = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
self.menuArray=response[@"menu"]; //Assign to array
[self.tableView reloadData];
现在,要设置表,首先在 viewDidLoad 方法中分配数据源和委托(delegate)
- (void)viewDidLoad {
self.tableView.dataSource=self;
self.tableView.delegate=self;
}
现在,实现 TableView 数据源方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//Want as many cells as in array
return self.menuArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"menuCell"];
if (cell==nil) {
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"defaultCell"];
}
//Display name of current item in array
cell.textLabel.text=[[self.menuArray objectAtIndex:indexPath.row]objectForKey:@"name"];
return cell;
}
现在,您应该已经完全设置好表格并显示名称。现在要将 url 传递给下一个 Controller ,您需要实现另一个方法。
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//Create new controller
ViewController *vc=[[ViewController alloc]initWithNibName:@"ViewController" bundle:nil];
//Pass it the url
vc.url=[[self.menuArray objectAtIndex:indexPath.row]objectForKey:@"url"];
//Present it
[self presentViewController:vc animated:YES completion:nil];
}
关于ios - 在 DrawerMenu Tableview 上显示数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38955873/