iOS学习笔记(5)——显示简单的TableView

1. 创建工程

  • 创建一个新的Xcode工程命名为SimpleTableTest。
  • 删除main.storyboard文件和info.plist中有关storyboard的相关属性。
  • 按command+F键创建TableViewController视图控制器(继承自UIViewController)和xib视图文件(此时,系统将默认xib视图文件的File's Owner是TableViewController视图控制器类)。

2. 创建xib文件

  • 选定View视图,并按下option+command+3切换到Attributes inspector,调整模拟器尺寸为4inch(默认是pad的尺寸,调小即可)。
  • 按下option+command+control+3打开Object library,选中tableview并拖到视图View上。
  • 选定Table View视图,按下option+command+6打开Connections inspector,将Outlets中的delegate和dataSource与File's Owner(TableViewController视图控制器)关联。

3. 编写代码

TableViewController.h

1 #import <UIKit/UIKit.h>
2 
3 @interface TableViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>//遵循tableview的委托协议和数据源协议
4 
5 @property (copy, nonatomic) NSArray *tableData;
6 @end

TableViewController.m

 1 #import "TableViewController.h"
 2 
 3 @interface TableViewController ()
 4 
 5 @end
 6 
 7 @implementation TableViewController
 8 
 9 - (void)viewDidLoad {
10     [super viewDidLoad];
11     // Do any additional setup after loading the view from its nib.
12     self.tableData = @[@"Bob", @"Fenndy", @"Neo", @"Lucky", @"Lily", @"Lucy", @"Jone", @"Kate", @"Sunny", @"Fenndy", @"Greeny", @"Brown", @"Jack", @"Andy"];
13     self.tableData = [self.tableData sortedArrayUsingSelector:@selector(compare:)];
14 }
15 
16 - (void)didReceiveMemoryWarning {
17     [super didReceiveMemoryWarning];
18     // Dispose of any resources that can be recreated.
19 }
20 
21 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
22     return [self.tableData count];
23 }
24 
25 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
26     static NSString *Identifier = @"Cell";
27     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Identifier];
28     if (cell == nil) {
29         cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Identifier];
30     }
31     cell.textLabel.text = self.tableData[indexPath.row];
32     return cell;
33 }
34 /*
35 #pragma mark - Navigation
36 
37 // In a storyboard-based application, you will often want to do a little preparation before navigation
38 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
39     // Get the new view controller using [segue destinationViewController].
40     // Pass the selected object to the new view controller.
41 }
42 */
43 
44 @end

AppDelegate.h

1 #import <UIKit/UIKit.h>
2 
3 @interface AppDelegate : UIResponder <UIApplicationDelegate>
4 
5 @property (strong, nonatomic) UIWindow *window;
6 
7 
8 @end

AppDelegate.m

 1 #import "AppDelegate.h"
 2 #import "TableViewController.h"
 3 
 4 @interface AppDelegate ()
 5 
 6 @end
 7 
 8 @implementation AppDelegate
 9 
10 
11 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
12     self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
13     // Override point for customization after application launch.
14     self.window.rootViewController = [[TableViewController alloc] initWithNibName:@"TableViewController" bundle:nil];
15     self.window.backgroundColor = [UIColor whiteColor];
16     [self.window makeKeyAndVisible];
17     return YES;
18 }
19 
20 - (void)applicationWillResignActive:(UIApplication *)application {
21     // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
22     // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
23 }
24 
25 - (void)applicationDidEnterBackground:(UIApplication *)application {
26     // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
27     // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
28 }
29 
30 - (void)applicationWillEnterForeground:(UIApplication *)application {
31     // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
32 }
33 
34 - (void)applicationDidBecomeActive:(UIApplication *)application {
35     // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
36 }
37 
38 - (void)applicationWillTerminate:(UIApplication *)application {
39     // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
40 }
41 
42 @end

TableViewController.h

1 #import <UIKit/UIKit.h>
2 
3 @interface TableViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>//遵循tableview的委托协议和数据源协议
4 
5 @property (copy, nonatomic) NSArray *tableData;
6 @end

TableViewController.m

 1 #import "TableViewController.h"
 2 
 3 @interface TableViewController ()
 4 
 5 @end
 6 
 7 @implementation TableViewController
 8 
 9 - (void)viewDidLoad {
10     [super viewDidLoad];
11     // Do any additional setup after loading the view from its nib.
12     self.tableData = @[@"Bob", @"Fenndy", @"Neo", @"Lucky", @"Lily", @"Lucy", @"Jone", @"Kate", @"Sunny", @"Fenndy", @"Greeny", @"Brown", @"Jack", @"Andy"];
13     self.tableData = [self.tableData sortedArrayUsingSelector:@selector(compare:)];
14 }
15 
16 - (void)didReceiveMemoryWarning {
17     [super didReceiveMemoryWarning];
18     // Dispose of any resources that can be recreated.
19 }
20 
21 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
22     return [self.tableData count];
23 }
24 
25 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
26     static NSString *Identifier = @"Cell";
27     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Identifier];
28     if (cell == nil) {
29         cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Identifier];
30     }
31     cell.textLabel.text = self.tableData[indexPath.row];
32     return cell;
33 }
34 /*
35 #pragma mark - Navigation
36 
37 // In a storyboard-based application, you will often want to do a little preparation before navigation
38 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
39     // Get the new view controller using [segue destinationViewController].
40     // Pass the selected object to the new view controller.
41 }
42 */
43 
44 @end

4. 小结

  • 若要实现TableView必须遵循UITableViewDataSource, UITableViewDelegate协议
  • 必须实现

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 两个方法。

  • - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 方法返回一个分区的表视图单元的行数。
  • - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 方法返回一个表视图单元。
  • 表视图的每一行都是一个表视图单元的实例。
  • 对于iOS而言,如果表视图不管表视图单元显示与否,都为表中的每一行分配一个表视图单元,那么就会造成大量的开销。因此,iOS利用重用机制显示表视图单元,当表视图单元滚离屏幕时,他们将放置在一个可重用的单元队列中。如果系统运行较慢,表视图将从队列中删除这些单元,以释放空间。
  • 标识符Identifier的作用:如果,滚动到屏幕上的新行重新使用滚离屏幕的一个单元,iOS系统利用tableview的重用机制就能避免不断创建和释放那些视图的开销。但是,需要表视图给出前面使用过的制定类型的单元,因此使用一个标识符来标明重用单元。
  • TableViewController既是视图的File's Owner,也是TableView的delegate和dataSource,实现tableview的具体方法,并提供tableview所需的数据源。
原文地址:https://www.cnblogs.com/nycoder/p/4369504.html