簡體   English   中英

如何將單元格添加到uitableview

[英]how to add cell to uitableview

我正在嘗試使用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];
}

另外,您應該在.h文件中將HomeViewController注冊到UITableViewDelegate / UITableViewDataSource協議。

將行更改為:

@interface HomeViewController : UIViewController <UITableViewDelegate,UITableViewDataSource>{

然后,在IB / Storyboard中,您需要將Connections Inspector下的tableView1delegatedataSource出口鏈接到HomeViewController

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM