我是 iOS 新手,只是试图让数据显示在UITableView
. 我基本上有一个关于作者的项目。我想显示作者姓名等。所以我有一个作者模型,AuthorsViewController
它是数据源和委托UITableView
等。我正在使用故事板(MainStoryboard
)表视图并设法将其连接到AuthorsViewController
“身份检查器”中。
如果有帮助,请提供 Storyboard 的图片,谢谢:
这里首先是模型:Author.h
#import <Foundation/Foundation.h>
@interface Author : NSObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *book;
@property (nonatomic) int year;
@end
作者.m
#import "Author.h"
@implementation Author
@end
这是 AuthorsViewController.h
@interface AuthorViewController : UITableViewController
<UITableViewDataSource, UITableViewDelegate>
@end
和 AuthorsViewController.m
#import "AuthorViewController.h"
@interface AuthorViewController ()
@property (nonatomic, strong) NSMutableArray *authors;
@end
@implementation AuthorViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
_authors = [[NSMutableArray alloc] init];
Author *auth = [[Author alloc] init];
[auth setName:@"David Powers"];
[auth setBook:@"PHP Solutions"];
[auth setYear:2010];
[_authors addObject:auth];
auth = [[Author alloc] init];
[auth setName:@"Lisa Snyder"];
[auth setBook:@"PHP security"];
[auth setYear:2011];
[_authors addObject:auth];
auth = [[Author alloc] init];
[auth setName:@"Rachel Andrew"];
[auth setBook:@"CSS3 Tips, Tricks and Hacks"];
[auth setYear:2012];
[_authors addObject: auth];
}
#pragma mark - 表格视图数据源
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [_authors count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"AuthorCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell != nil)
{
cell = [[UITableViewCell alloc]
initWithStyle: UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Author *currentAuthor = [_authors objectAtIndex:[indexPath row]];
[[cell textLabel] setText: [currentAuthor name]];
NSLog(@"%@", [currentAuthor name]);
return cell;
}
@end