iPhone第三节:UITableView(2)

UITableView(2)练习(微博)、课堂(相册)


练习==微博

Model==Blog

#import <Foundation/Foundation.h>

@interface Blog : NSObject

#pragma mark - 属性
@property (nonatomic,assign) long long Id;//微博id
@property (nonatomic, strong) NSString *profileImageUrl;//头像
@property (nonatomic, strong) NSString *userName;//发送用户
@property (nonatomic, strong) NSString *mbtype;//会员类型
@property (nonatomic, strong) NSString *createdAt;//创建时间
@property (nonatomic, strong) NSString *source;//设备来源
@property (nonatomic, strong) NSString *text;//微博内容

#pragma mark - 方法
#pragma mark 根据字典初始化微博对象
-(Blog *)initWithDictionary:(NSDictionary *)dic;

#pragma mark 初始化微博对象(静态方法)
+(Blog *)blogWithDictionary:(NSDictionary *)dic;

@end
#import "Blog.h"

@implementation Blog

#pragma mark 根据字典初始化微博对象
-(Blog *)initWithDictionary:(NSDictionary *)dic
{
    if(self = [super init])
    {
        self.Id = [dic[@"Id"] longLongValue];
        self.profileImageUrl = dic[@"profileImageUrl"];
        self.userName = dic[@"userName"];
        self.mbtype = dic[@"mbtype"];
        self.createdAt = dic[@"createdAt"];
        self.source = dic[@"source"];
        self.text = dic[@"text"];
    }
    return self;
}

#pragma mark 初始化微博对象(静态方法)
+(Blog *)blogWithDictionary:(NSDictionary *)dic
{
    Blog *blog = [[Blog alloc]initWithDictionary:dic];
    return blog;
}

-(NSString *)source
{
    return [NSString stringWithFormat:@"来自 %@",_source];
}
@end
View==BlogTableViewCell

#import <UIKit/UIKit.h>
@class Blog;
@interface BlogTableViewCell : UITableViewCell

#pragma mark 微博对象
@property (nonatomic, strong) Blog *blog;

#pragma mark 单元格高度
@property (assign, nonatomic) CGFloat height;

@end
#import "BlogTableViewCell.h"
#import "Blog.h"
#import "QuartzCore/QuartzCore.h"

@interface BlogTableViewCell()
{
    UIImageView *_avatar;//头像
    UIImageView *_mbType;//会员类型
    UILabel *_userName;
    UILabel *_createAt;
    UILabel *_source;
    UILabel *_text;
}

@end

@implementation BlogTableViewCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self)
    {
        //头像
        _avatar = [[UIImageView alloc] init];
        [self.contentView addSubview:_avatar];
        
        //用户名
        _userName = [[UILabel alloc] init];
        _userName.textColor = [UIColor blackColor];
        _userName.font=[UIFont systemFontOfSize:14.0];
        [self.contentView addSubview:_userName];
        
        //会员类型
        _mbType = [[UIImageView alloc] init];
        [self.contentView addSubview:_mbType];
        //圆角view
        _mbType.layer.cornerRadius = 5;//(像素一半,为圆形,小于一半,为原图形圆角,数值越大圆角越大)
        _mbType.layer.masksToBounds = YES;
        //边框宽度及颜色设置
//        [_mbType.layer setBorderWidth:2];
//        [_mbType.layer setBorderColor:([UIColor blueColor]).CGColor];  //设置边框为蓝色
        //自动适应,保持图片宽高比
        _mbType.contentMode = UIViewContentModeScaleAspectFit;
        
        
        //日期
        _createAt = [[UILabel alloc] init];
        _createAt.textColor = [UIColor lightGrayColor];
        _createAt.font = [UIFont systemFontOfSize:12.0];
        [self.contentView addSubview:_createAt];
        
        //设备
        _source = [[UILabel alloc] init];
        _source.textColor = [UIColor lightGrayColor];
        _source.font = [UIFont systemFontOfSize:12.0];
        [self.contentView addSubview:_source];
        
        //内容
        _text = [[UILabel alloc] init];
        _text.textColor = [UIColor blackColor];
        _text.font = [UIFont systemFontOfSize:14];
        _text.numberOfLines = 0;
        //_text.lineBreakMode = NSLineBreakByWordWrapping;
        [self.contentView addSubview:_text];
    }
    return self;
}

- (void)setBlog:(Blog *)blog
{
    _avatar.frame = CGRectMake(10, 10, 40, 40);
    _avatar.image = [UIImage imageNamed:blog.profileImageUrl];
    
    CGSize userNameSize = [blog.userName sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:14]}];
    CGRect userNameRect=CGRectMake(60, 10, userNameSize.width,userNameSize.height);
    _userName.frame = userNameRect;
    _userName.text = blog.userName;
    
    _mbType.frame = CGRectMake((CGRectGetMaxX(_userName.frame) + 5), 12, 13, 13);
    _mbType.image = [UIImage imageNamed:blog.mbtype];
    
    CGSize createAtSize=[blog.createdAt sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12]}];
    CGFloat createAtY = 50 - createAtSize.height;
    CGRect createAtRect = CGRectMake(60, createAtY, createAtSize.width, createAtSize.height);
    _createAt.frame = createAtRect;
    _createAt.text = blog.createdAt;
    
    CGSize sourceSize = [blog.source sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:12]}];
    CGFloat sourceX = CGRectGetMaxX(_createAt.frame) + 10;
    CGFloat sourceY = createAtY;
    CGRect sourceRect = CGRectMake(sourceX, sourceY, sourceSize.width,sourceSize.height);
    _source.frame = sourceRect;
    _source.text = blog.source;
    
    CGSize textSize = [blog.text boundingRectWithSize:CGSizeMake(self.frame.size.width - 20, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:14]} context:nil].size;
    _text.frame = CGRectMake(10, 60, textSize.width, textSize.height);
    _text.text = blog.text;
    
    _height = CGRectGetMaxY(_text.frame) + 10;
    
}

#pragma mark 重写选择事件,取消选中
-(void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    
}

- (void)awakeFromNib
{
    // Initialization code
}

//- (void)setSelected:(BOOL)selected animated:(BOOL)animated
//{
//    [super setSelected:selected animated:animated];
//
//    // Configure the view for the selected state
//}

@end
Controller==BlogViewController

#import "BlogViewController.h"
#import "Blog.h"
#import "BlogTableViewCell.h"


@interface BlogViewController () <UITableViewDataSource, UITableViewDelegate, UIAlertViewDelegate>

{
    UITableView * blogTableView;
    NSMutableArray * blogArray;
    NSMutableArray * cellArray;
}

@end

@implementation BlogViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)initTableView
{
    //位置,大小,风格
    blogTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    [self.view addSubview:blogTableView];
    //代理、数据源
    blogTableView.dataSource = self;
    blogTableView.delegate = self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self initTableView];
    
    [self initData];
    
}

- (void)initData
{
    NSString * path = [[NSBundle mainBundle] pathForResource:@"BlogList" ofType:@"plist"];
    NSArray * array = [NSMutableArray arrayWithContentsOfFile:path];
    blogArray = [[NSMutableArray alloc] init];
    cellArray = [[NSMutableArray alloc] init];
    [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        [blogArray addObject:[Blog blogWithDictionary:obj]];
        BlogTableViewCell *cell=[[BlogTableViewCell alloc]init];
        [cellArray addObject:cell];
    }];
}

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

//行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return blogArray.count;
}

//返回每行的单元格
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellId = @"UITableViewCellIdentifierKey1";
    BlogTableViewCell *blogCell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if(!blogCell)
    {
        blogCell = [[BlogTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }
    //分别赋值
    Blog * model = blogArray[indexPath.row];
    blogCell.blog = model;
    return blogCell;
}

#pragma mark 重新设置单元格高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BlogTableViewCell *cell= cellArray[indexPath.row];
    cell.blog = blogArray[indexPath.row];
    return cell.height;
}

#pragma mark 重写状态样式方法
-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

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

@end

课堂==相册

Model==Work

#import <Foundation/Foundation.h>

@interface Work : NSObject

@property (nonatomic, strong) NSString * imageWork;
@property (nonatomic, strong) NSString * titleText;
@property (nonatomic, strong) NSString * numText;

- (id)initWithImage:(NSString *)_imageWork andTitle:(NSString *)_titleText andNum:(NSString *)_numText;

@end
#import "Work.h"

@implementation Work

@synthesize imageWork, titleText, numText;

- (id)initWithImage:(NSString *)_imageWork andTitle:(NSString *)_titleText andNum:(NSString *)_numText
{
    if (self = [super init])
    {
        self.imageWork = _imageWork;
        self.titleText = _titleText;
        self.numText = _numText;
    }
    return self;
}

@end
View==WorkTableViewCell

#import <UIKit/UIKit.h>

@interface WorkTableViewCell : UITableViewCell

@property (nonatomic, strong)UIImageView * workImageView;
@property (nonatomic, strong)UILabel * titleLabel;
@property (nonatomic, strong)UILabel * numLabel;

@end
#import "WorkTableViewCell.h"
#import "GlobalDefine.h"


@implementation WorkTableViewCell

#define RECT(Y) CGRectMake(90, Y, SCWIDTH - 90 - 20, 40)

@synthesize workImageView, titleLabel, numLabel;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self)
    {
        workImageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 70, 70)];
        [self.contentView addSubview:workImageView];
        
        titleLabel = [[UILabel alloc] initWithFrame:RECT(15)];
        titleLabel.font = [UIFont systemFontOfSize:14.0];
        titleLabel.textColor = [UIColor blackColor];
        titleLabel.backgroundColor = [UIColor clearColor];
        titleLabel.textAlignment = NSTextAlignmentLeft;
        [self.contentView addSubview:titleLabel];
        
        numLabel = [[UILabel alloc] initWithFrame:RECT(35)];
        numLabel.font = [UIFont systemFontOfSize:14.0];
        numLabel.textColor = [UIColor blackColor];
        numLabel.backgroundColor = [UIColor clearColor];
        numLabel.textAlignment = NSTextAlignmentLeft;
        [self.contentView addSubview:numLabel];
    }
    return self;
}

- (void)awakeFromNib
{
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end

Controller==ViewControllerTable

#import <UIKit/UIKit.h>

@interface ViewControllerTable : UIViewController

@property (nonatomic, strong) UITableView * tableViewWork;
@property (nonatomic, strong) NSMutableArray * modelArray;

@end
#import "ViewControllerTable.h"
#import "WorkTableViewCell.h"
#import "GlobalDefine.h"
#import "Work.h"

@interface ViewControllerTable () <UITableViewDataSource, UITableViewDelegate, UIAlertViewDelegate>

{
    BOOL add;  //判断是否是 添加
}

@end

@implementation ViewControllerTable

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
//初始化tableView
- (void)initTableView
{
    //位置,大小,风格
    _tableViewWork = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCWIDTH, SCHEIGHT) style:UITableViewStylePlain];
    [self.view addSubview:_tableViewWork];
    //代理、数据源
    _tableViewWork.dataSource = self;
    _tableViewWork.delegate = self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];
    //初始化
    [self initTableView];
    //可变数组,盛放模型
    _modelArray = [[NSMutableArray alloc] initWithCapacity:1];
    //初始化模型,并放入数组
    for (int i = 0; i < 10; i++)
    {
        Work * workModel = [[Work alloc] initWithImage:[NSString stringWithFormat:@"%d.jpg", i] andTitle:[NSString stringWithFormat:@"Title %d", i + 1] andNum:[NSString stringWithFormat:@"共有%d张图片", i + 1]];
        [_modelArray addObject:workModel];
    }
    
#pragma mark ==deleteButton
    UIButton * deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
    deleteButton.frame = CGRectMake(230, 40, 50, 20);
    deleteButton.showsTouchWhenHighlighted = YES;
    [deleteButton setTitle:@"删除" forState:UIControlStateNormal];
    [deleteButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [deleteButton addTarget:self action:@selector(delete) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:deleteButton];
    
#pragma mark ==addButton
    UIButton * addButton = [UIButton buttonWithType:UIButtonTypeCustom];
    addButton.frame = CGRectMake(230, 20, 50, 20);
    addButton.showsTouchWhenHighlighted = YES;
    [addButton setTitle:@"添加" forState:UIControlStateNormal];
    [addButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [addButton addTarget:self action:@selector(add) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:addButton];
    
#pragma mark ==backButton
    UIButton * backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(230, SCHEIGHT - 50, 50, 20);
    backButton.showsTouchWhenHighlighted = YES;
    [backButton setTitle:@"返回" forState:UIControlStateNormal];
    [backButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backButton];

}
//行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_modelArray count];
}
//每行单元格
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //缓存池标识
    static NSString * cellId = @"reuseCellId";
    //到缓存池寻找cell
    WorkTableViewCell * workCell = [tableView dequeueReusableCellWithIdentifier:cellId];
    //如果没有则新建,并放入缓存池
    if (!workCell)
    {
        workCell = [[WorkTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }
    //当前行的对象模型
    Work * model = [_modelArray objectAtIndex:indexPath.row];
    //分别赋值
    workCell.workImageView.image = [UIImage imageNamed:model.imageWork];
    workCell.titleLabel.text = model.titleText;
    workCell.numLabel.text = model.numText;
    
    return workCell;
}
//行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 90.0;
}
//删除,add置NO,进入编辑状态,刷新
- (void)delete
{
    add = NO;
    [self.tableViewWork setEditing:YES animated:YES];
    [self.tableViewWork reloadData];
}

- (void)add
{
    add = YES;
    [self.tableViewWork setEditing:YES animated:YES];
    [self.tableViewWork reloadData];
}
//返回,提示
- (void)back
{
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"退出编辑模式?" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
}
//点击确定退出编辑模式
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1)
    {
        [self.tableViewWork setEditing:NO];
    }
}
//根据add,判断进入删除或者插入(默认删除)
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;//多选
    if (add)
    {
        return UITableViewCellEditingStyleInsert;
    }
    return UITableViewCellEditingStyleDelete;
}
//根据删除、插入状态,进行相应操作,并在操作完成后退出编辑模式
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        [_modelArray removeObjectAtIndex:indexPath.row];
        
        NSIndexPath * path = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section];
        [_tableViewWork deleteRowsAtIndexPaths:[NSArray arrayWithObject:path] withRowAnimation:UITableViewRowAnimationFade];
        [self.tableViewWork setEditing:NO];
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert)
    {
        Work * workModel = [[Work alloc] initWithImage:[NSString stringWithFormat:@"1.jpg"] andTitle:[NSString stringWithFormat:@"Title %d", indexPath.row + 1] andNum:[NSString stringWithFormat:@"共有%d张图片", indexPath.row + 1]];
        [_modelArray insertObject:workModel atIndex:indexPath.row];
        NSIndexPath * path = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section];
        [_tableViewWork insertRowsAtIndexPaths:[NSArray arrayWithObject:path] withRowAnimation:UITableViewRowAnimationFade];
        [self.tableViewWork setEditing:NO];
    }
}

//改变 删除的delete字样
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}

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

@end


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值