0

我创建了一个数组,它的数据显示在表格视图中。现在我想将字典数据添加到该数组并在同一个表视图中显示。我创建了一个按钮,它将字典值添加到数组中,但我无法在 tableview 中看到数据。

这是我的“ViewController.m”

#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
mArray = [[NSMutableArray alloc]initWithObjects:@"one",@"two",@"three",@"four",@"five",@"six",@"seven",@"eight",@"nine",@"ten", nil];
mDictionary = [[NSMutableDictionary alloc]init];
[mDictionary setValue:@"gfhhgfhf" forKey:@"firstname"];
[mDictionary setValue:@"hhgghf" forKey:@"lastname"];
CGRect frame = self.view.frame;
UITableView *tableView = [[UITableView alloc]initWithFrame:frame style:UITableViewStylePlain];
tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
tableView.backgroundColor = [UIColor cyanColor];
tableView.separatorColor = [UIColor blackColor];
tableView.delegate = self;
tableView.dataSource = self;
UIButton *button = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
button.frame = CGRectMake(200, 400, 100, 30);
[button setTitle:@"ADD" forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[button addTarget:self action:@selector(addValueInArray) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:tableView];
[self.view addSubview:button];
}
-(void)addValueInArray{
[mArray addObject:(mDictionary)];
[mArray reloadData];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return mArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:  (NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
if (!cell) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault   reuseIdentifier:@"cell"];
}
cell.textLabel.text = [mArray objectAtIndex:indexPath.row];
    return cell;
}
- (void)dealloc
{
[mArray release];
[super dealloc];
}
@end
4

2 回答 2

1

使用它并替换您的功能。它会起作用的

   -(void)addValueInArray{
   [mArray addObject:[[mDictionary objectForKey:@"firstname"]stringByAppendingString:[mDictionary objectForKey:@"lastname"]];
   [tableView reloadData];
    }
于 2013-01-31T06:24:22.723 回答
1

你可以mArray 通过这样做来填写你的 ->

-(void)addValueInArray{
   [[mArray addObject:[[mDictionary objectForKey:@"firstname"]stringByAppendingString:[mDictionary objectForKey:@"lastname"]]];
   [tableView reloadData];
    }

然后,在您的表视图委托方法中,执行此操作->

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:  (NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
if (!cell) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault   reuseIdentifier:@"cell"];
}
cell.textLabel.text = [mArray objectAtIndex:indexPath.row];
    return cell;
}

希望能帮助到你...

于 2013-01-31T06:32:30.977 回答