gpt4 book ai didi

ios - 如何将单元格添加到uitableview

转载 作者:行者123 更新时间:2023-11-29 03:45:52 24 4
gpt4 key购买 nike

我正在尝试使用 IBAction 将新单元格添加到 UITableview 中,但是当我按下模拟器上的添加按钮时,什么也没有发生。经过几个小时对 stackoverflow 和 google 的研究,我想出了这段代码。我认为它应该有效,但我不明白为什么它不起作用。

请帮忙!!!

我的.h文件

@interface HomeViewController : UIViewController{
NSMutableArray *countries;
}


- (IBAction)addFav:(id)sender;
@property (nonatomic, strong) IBOutlet UITableView *tableView1;



@end

和我的 .m 文件

#import "HomeViewController.h"


@interface HomeViewController ()

@end

@implementation HomeViewController{

}
@synthesize tableView1;

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
countries = [NSMutableArray new];
}




- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [countries count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = @"Cell";

UITableViewCell *cell = [tableView1 dequeueReusableCellWithIdentifier:simpleTableIdentifier];

if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}

cell.textLabel.text = [countries objectAtIndex:indexPath.row];
return cell;
}


- (IBAction)addFav:(id)sender {
[tableView1 beginUpdates];
[countries addObject:@"Finland"];
NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:([countries count] - 1) inSection:0];
[self.tableView1 insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationRight];
[tableView1 endUpdates];
[tableView1 reloadData];
}

@end

任何帮助将不胜感激

谢谢

最佳答案

如果您一次只添加一项,则可以考虑将 addFav 方法修改为以下内容:

- (IBAction)addFav:(id)sender {
//[tableView1 beginUpdates];
[countries addObject:@"Finland"];
//NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:([countries count] - 1) inSection:0];
//[self.tableView1 insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationRight];
//[tableView1 endUpdates];
[tableView1 reloadData];
}

此外,您应该将 HomeViewController 注册到 .h 文件中的 UITableViewDelegate/UITableViewDataSource 协议(protocol)。

将行更改为:

@interface HomeViewController : UIViewController <UITableViewDelegate,UITableViewDataSource>{

然后在 IB/Storyboard 中,您需要将 Connections Inspector 下 tableView1delegatedataSource 导出链接到您的 HomeViewController.

关于ios - 如何将单元格添加到uitableview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17772365/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com