背景知识

每个表都是UITableView的实例,表中的每一行都是UITableViewCell的实例。

 

TableView的种类

  • Grouped table
  • Plain table without index
  • Plain table with index

简单的TableView

NSIndexPath

  • NSIndexPath.section 返回int,表示第几个Section
  • NSIndexPath.row 返回int,表示该Section下的第几行

UITableViewCell包含的元素

  • Image    (imageView.image)
  • Text Label (textLabel.text, textLabel.font)
  • Detail Text Label (detailTextLabel.text)

UITableViewCell样式

  • UITableViewCellStyleDefault   //左文,图(如果有则最左)
  • UITableViewCellStyleSubtitile   //左文,图(如果有则最左),detailText在Text下面
  • UITableViewCellStyleValue1        //左文,图(如果有则最左),detailText在最右
  • UITableViewCellStyleValue2        //左文,图(如果有则最左),detailText在Text右边

 简单的TableView

简单例子

StoryBoard拖入一个TableView,然后设置DataSource和Delegate为ViewController。
ViewController.h声明协议

#import <UIKit/UIKit.h>

@interface XYZViewController : UIViewController<UITableViewDataSource, UITableViewDelegate>
@end

 

ViewController.m文件如下

//
//  XYZViewController.m
//  TableView
//
//  Created by Norcy on 14-7-24.
//  Copyright (c) 2014年 QQLive. All rights reserved.
//

#import "XYZViewController.h"

@interface XYZViewController ()
@property (strong, nonatomic)NSArray *array;
@end

@implementation XYZViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    self.array = [[NSArray alloc] initWithObjects:@"1", @"2", @"3", @"4", @"5", @"6", @"7", @"8", @"9", @"10", @"11", @"12", @"13", @"14", @"15", nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -
#pragma mark Data Source Methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.array count];
}

#pragma mark Delegate Methods
- (UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellId = @"MyCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellId];
    }
    
    cell.textLabel.text = self.array[indexPath.row];
    
    UIImage *image = [UIImage imageNamed:@"1.png"];
    
    cell.imageView.image = image;
    
    cell.detailTextLabel.text = @"Details";
    
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return indexPath.row;
}
@end
View Code

相关文章: