[英]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下的tableView1
的delegate
和dataSource
出口鏈接到HomeViewController
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.