iOS UITableView 与 UITableViewController实例详解

2020-01-18 15:58:57丽君

  UITableViewDataSource 协议中的另外一个必须实现的方法

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  在此之前,我们需要先了解另一个类:UITableViewCell

•UITableViewCell 对象

  表视图所显示的每一行都是一个独立的视图,这些视图是 UITableViewCell 对象。其对象还有一个子视图:contentView 。contentView 也包含了很多子视图,他的子视图构成 UITableViewCell 对象的主要外观。此外, UITableViewCell 对象还可以显示一个辅助指示图。辅助指示视图的作用是显示一个指定的图标,用于向用户提示 UITableViewCell 对象可以执行的动作。这些图标包括勾起标记、展开图标或中间有v形团的蓝色圆点。其默认是 UITableViewCellAccessoryNone 。

  在创建 UITableViewCell 对象时,可以选择不同的风格来决定 UITableViewCell 对象显示。


typedef NS_ENUM(NSInteger, UITableViewCellStyle) {
UITableViewCellStyleDefault, // Simple cell with text label and optional image view (behavior of UITableViewCell in iPhoneOS 2.x)
UITableViewCellStyleValue1, // Left aligned label on left and right aligned label on right with blue text (Used in Settings)
UITableViewCellStyleValue2, // Right aligned label on left with blue text and left aligned label on right (Used in Phone/Contacts)
UITableViewCellStyleSubtitle // Left aligned label on top and left aligned label on bottom with gray text (Used in iPod).
}; // available in iPhone OS 3.0

  创建并获取 UITableViewCell 对象

  下面我们主要对 tableView: cellForRowAtIndexPath: 方法进行改写。首先我们需要将 JXItem 数据跟 UITableViewCell 对象对应起来。在方法中有一个实参是 NSIndexPath 对象,该对象包含两个属性 section(段) 和 row(行) 。当 UITableView 对象向其数据源发送 tableView: cellForRowAtIndexPath: 消息时,其目的是获取显示第 section 个表格段、第 row 行数据的 UITableViewCell 对象。


#import "JXItemsViewController.h"
#import "JXItem.h"
#import "JXItemStore.h"
@interface JXItemsViewController ()
@end
@implementation JXItemsViewController
- (instancetype)init {
// 调用父类的指定初始化方法
self = [super initWithStyle:UITableViewStylePlain];
if (self) {
for (NSInteger i=0; i<15; i++) {
[[JXItemStore sharedStore] createItem];
}
}
return self;
}
- (instancetype)initWithStyle:(UITableViewStyle)style {
return [self init];
}
- (void)viewDidLoad {
[super viewDidLoad];
}
#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [[[JXItemStore sharedStore] allItem] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// 创建 UITableViewCell 对象,风格使用默认风格
UITableViewCell * cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:@"UITableViewCell"];
// 获取 allItem 的第 n 个 JXItem 对象
// 然后将该 JXItem 对象的描述信息赋值给 UITableViewCell 对象的 textLabel
// 这里的 n 是该 UITableViewCell 对象所对应的表格索引
NSArray * items = [[JXItemStore sharedStore] allItem];
JXItem * item = items[indexPath.row];
cell.textLabel.text = [item description];
return cell;
}
@end