UITableView表视图

UITableViewDataSource,UITableViewDelegate UITabelView表视图的俩个协议,
UITableViewDataSource这个协议中的俩个必须执行的方法

@required
//显示多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
//每行显示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;

点击选中单元格的时候执行的方法

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%@",indexPath);
}

设置头部区域的高度 注意:在自定义头部文本的时候 默认的不用写 但是头部区域的高度一定要写 正确使用这个的高度显示 不然不会出现头部文本

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 60;
}

给分区头部自定义视图

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UILabel *footLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 375, 60)];
    footLabel.text = @"食物";
    footLabel.font = [UIFont boldSystemFontOfSize:30];
    footLabel.textAlignment = NSTextAlignmentCenter;
    
    UILabel *bookLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 375, 0)];
    bookLabel.text = @"四大名族";
    bookLabel.font = [UIFont boldSystemFontOfSize:30];
    bookLabel.textAlignment = NSTextAlignmentCenter;
    
    UILabel *gameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 375, 60)];
    gameLabel.text = @"游戏";
    gameLabel.font = [UIFont boldSystemFontOfSize:30];
    gameLabel.textAlignment = NSTextAlignmentCenter;
    switch (section) {
        case 0:
            return footLabel;
            break;            
        case 1:
            return bookLabel;
            break;
        case 2:
            return gameLabel;
            break;            
        default:
            break;
    }
    return nil;
}

设置分区头部显示文本

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{    
    switch (section) {
        case 0:
            return @"食物";
            break;
        case 1:
            return @"四大名族";
            break;
        case 2:
            return @"游戏";
            break;
        default:
            break;
    }
    return nil;
}

//设置表视图的分区个数

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

小技巧 :何时需要重写loadView方法???
1.RootViewController继承自UIViewController,继承了loadView方法,可以给自定的视图指定新视图
2.UIViewController 通过loadView方法创建的视图是一个空视图,如果我们的需求不是空视图,那么就需要我们自己创建一个视图,指定给self.view,此时需要重写loadView方法

 posted on 2015-05-02 11:05  ianhao_cn  阅读(170)  评论(0编辑  收藏  举报