应用程序之Xib自定义Cell

  • 效果展示
  • 结构分析
  • 代码实现

一、效果展示

二、结构分析

1⃣️首先我们让我们的控制器不再继承UIViewController,而是继承UITableViewController。这样就直接遵守了delegate协议、dataSource协议

2⃣️数据使用模型来加载

3⃣️自定义的Cell使用单独的类来管理

三、代码实现

//
//  BookController.m
//  01-自定义cell04
//
//  Created by apple on 14-4-9.
//  Copyright (c) 2014年 apple. All rights reserved.
//

#import "BookController.h"
#import "Book.h"
#import "BookCell.h"

@interface BookController ()
{
    NSMutableArray *books;
}
@end

@implementation BookController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    books = [NSMutableArray array];
    for (int i = 0; i<20; i++) {
        Book *b = [Book bookWithName:[NSString stringWithFormat:@"iOS开发%d", i] price:arc4random_uniform(200)/10.0 + 10];
        [books addObject:b];
    }

}

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return books.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    //加载的cell就是xib对应的BookCell对象
    BookCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"BookCell" owner:nil options:nil] lastObject];
        
    }
    
    Book *book = books[indexPath.row];
    cell.nameLabel.text = book.name;
    cell.priceLable.text = [NSString stringWithFormat:@"¥%.1f", book.price];
    
    UIButton *collect = cell.collectBtn;
    [collect addTarget:self action:@selector(collectClick: event:) forControlEvents:UIControlEventTouchUpInside];
    
    return cell;
}

- (void)collectClick:(UIButton*)btn event:(UIEvent*)event
{
    
    //NSLog(@"----%@", event);
    UITableView *tableView = (UITableView *)self.view;
    
    // 获取所有的触摸点(UITouch对象,如果是单点触碰,就只有1个UITouch)
    NSSet *touches = [event allTouches];
    
    // 一个UITouch对象对应一根手指
    UITouch *touch = [touches anyObject];
    
    // 获取触摸点在UITableView上面的的位置
    CGPoint position = [touch locationInView:tableView];
    
    // 根据触摸位置 得到 对应的行号
    NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:position];
    //NSLog(@"%d", indexPath.row);
    
    Book *book = books[indexPath.row];
    NSLog(@"%@", book.name);
}

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //取消选中蓝色
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}

@end

 

posted @ 2014-04-09 16:01  了透糕糟  阅读(195)  评论(0编辑  收藏  举报