iOS项目开发基础(封装网络请求、json转model、方法顺序、文件结构、TableView自动布局、计算文本内容大小等)

前沿:整理了一个项目开发基础,涉及到开发初期的必备条件与开发中可以遵循的编码规范。源码请点击github地址下载。

目录

一.封装网络请求

1.封装get请求

code1.png



2.封装post请求

code2.png



3.使用方法

[LXNetWorkTool get:urlStr param:param success:^(NSDictionary *responseDic) {

NSLog(@"%@", responseDic);

} failure:^(NSError *error) {

}];

二.json转model

获取到网络json数据后,无论多么复杂的数据结构,嵌套多少层,使用mj的一个第三方一句代码将字典转化成model,如下:

LXStockResult *resultModel = [LXStockResult objectWithKeyValues:responseDic];

但是必须先根据responseDic的数据结构定义好在LXStockResult的属性列表,如这样的数据结构:

screen1.png


需创建的model文件如下:

screen2.png


对应的属性列表如下:

@interface LXStockResult : NSObject
@property (nonatomic, strong) LXStockResponse *response;
@end

@interface LXStockResponse : NSObject
@property (nonatomic, strong) LXStockResponseStatus *responseStatus;
@property (nonatomic, strong) NSArray *stockList;
@end
@implementation LXStockResponse
+ (NSDictionary *)objectClassInArray
{
    return @{@"stockList":[LXStockList class]};
}
@end

@interface LXStockResponseStatus : NSObject
@property (nonatomic, copy)   NSString *status;
@property (nonatomic, copy)   NSString *statusInfo;
@end

@interface LXStockList : NSObject
@property (nonatomic, copy)   NSString *stockCode;
@property (nonatomic, copy)   NSString *stockName;
@end

三.方法顺序

#pragma mark - Life cycle
#pragma mark - Init data
#pragma mark - Loading data
#pragma mark - Create view
#pragma mark - UITableViewDelegate
#pragma mark - SystemDelegate
#pragma mark - CustomDelegate
#pragma mark - Observer
#pragma mark - Enent response
#pragma mark - Private methods
#pragma mark - Setter and getter



将方法顺序整理,利于快速查找方法,易于后期维护

展示效果如图:

screen4.png

四.文件结构

如下图:

screen3.png


有一个清晰的文件结构,利于理解业务与后期维护。

五.TableView自动布局

[LXNetWorkTool get:urlStr param:param success:^(NSDictionary *responseDic) {
    LXStockResult *resultModel = [LXStockResult objectWithKeyValues:responseDic];
    //这里将stockList模型数组再封装,通过model的数据与cell控件结合算出文本高。
    [self.showDataArr setArray:[self manageViewsFrameWithDatas:resultModel.response.stockList]];
    [self.tableView reloadData];
} failure:^(NSError *error) {
}];
- (NSArray *)manageViewsFrameWithDatas:(NSArray *)datas
{
    NSMutableArray *tempArr = [NSMutableArray array];
    for (LXStockList *listModel in datas) {
        LXTestStockFrame *frame = [[LXTestStockFrame alloc] init];
        frame.model = listModel;
        [tempArr addObject:frame];
    }
    return tempArr;
}
- (void)setModel:(LXStockList *)model
{
    _model = model;
    
    CGFloat stockNameLabelW = kScreenWidth - 2*globalAlignMargin;
    CGFloat stockNameLabelH = [LXHelpClass calculateLabelighWithText:model.stockName withMaxSize:CGSizeMake(stockNameLabelW, MAXFLOAT) withFont:18];
    self.stockNameLabelFrame = CGRectMake(globalAlignMargin, 12, stockNameLabelW, stockNameLabelH);
    
    CGFloat stockCodeLabelY = self.stockNameLabelFrame.origin.y + self.stockNameLabelFrame.size.height + 5;
    self.stockCodeLabelFrame = CGRectMake(self.stockNameLabelFrame.origin.x, stockCodeLabelY, 100, 12);
    
    self.cellHeight = self.stockCodeLabelFrame.origin.y + self.stockCodeLabelFrame.size.height + 12;
}

@interface LXTestStockFrame : NSObject
//数据源
@property (nonatomic, strong) LXStockList *model;
//cell高
@property (nonatomic, assign) CGFloat cellHeight;
//stockNameLabel的坐标
@property (nonatomic, assign) CGRect stockNameLabelFrame;
//stockCodeLabel的坐标
@property (nonatomic, assign) CGRect stockCodeLabelFrame;
@end

- (void)configurationCell:(LXTestStockFrame *)frameModel;
{
    self.stockNameLabel.frame = frameModel.stockNameLabelFrame;
    self.stockNameLabel.text = frameModel.model.stockName;
    
    self.stockCodeLabel.frame = frameModel.stockCodeLabelFrame;
    self.stockCodeLabel.text = frameModel.model.stockCode;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LXTestStockFrame *frame = self.showDataArr[indexPath.row];
    return frame.cellHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //如果有多种样式的cell,则可以根据区别indexPath.section或indexPath.row去创建不同的cell
    if (indexPath.section == 0) {
        LXTestTableCell *cell = [LXTestTableCell cellWithTableView:tableView];
        cell.row = indexPath.row;
        [cell configurationCell:self.showDataArr[indexPath.row]];
        return cell;
    } else {
        LXTestTableCell *cell = [LXTestTableCell cellWithTableView:tableView];
        cell.row = indexPath.row;
        [cell configurationCell:self.showDataArr[indexPath.row]];
        return cell;
    }
}

六.复用UITableViewHeaderFooterView

若UITableViewHeaderFooterView不采用复用机制,那么每次滑动TableView看见HeaderFooterView时都会掉用下面的代理方法从而不断重复创建

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    LXTestHeaderView *headerView = [LXTestHeaderView headerViewWithTableView:tableView];
    return headerView;
}

@implementation LXTestHeaderView
+ (instancetype)headerViewWithTableView:(UITableView *)tableView
{
    static NSString *headerId = @"headerView";
    LXTestHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headerId];
    
    if (headerView == nil) {
        headerView = [[LXTestHeaderView alloc] initWithReuseIdentifier:headerId];
    }
    
    return headerView;
}
- (instancetype)initWithReuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithReuseIdentifier:reuseIdentifier]) {
        self.backgroundColor = globalGrayColor;
        
        UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 44)];
        title.text = @"headerView也需要用复用池";
        title.textColor = globalRedWordColor;
        title.textAlignment = NSTextAlignmentCenter;
        title.font = [UIFont systemFontOfSize:18];
        [self addSubview:title];
    }
    return self;
}

七.计算文本内容大小

1.计算普通文本的高

+ (CGFloat)calculateLabelighWithText:(NSString *)textStr withMaxSize:(CGSize)maxSize withFont:(CGFloat)font
{
    NSDictionary * tdic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:font], NSFontAttributeName, nil];
    CGSize actualSize = [textStr boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:tdic context:nil].size;
    return actualSize.height;
}

2.计算富文本的高

#define GetLabelNormalHeight(height,font,spaceH) (height + (height - [UIFont systemFontOfSize:font].pointSize)*(spaceH>0 ? spaceH : 0.05))
/**
 *@param textStr 富文本的string属性的值
 *@param maxSize 控件所需最大空间,一般高是最大值,如:CGSizeMake(stockNameLabelW, MAXFLOAT)
 *@param font 字体大小
 *@param spaceRH label行距占行高的比例,若没有设置行高,默认值为0.05
 */
+ (CGFloat)calculateLabelighWithText:(NSString *)textStr withMaxSize:(CGSize)maxSize withFont:(CGFloat)font withSpaceRH:(CGFloat)spaceRH
{
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
    NSDictionary *dic = @{NSFontAttributeName: [UIFont systemFontOfSize:font], NSParagraphStyleAttributeName:paragraphStyle.copy};
    CGRect rect = [textStr boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    return GetLabelNormalHeight(rect.size.height, font, spaceRH);
}




我的github


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,340评论 5 467
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,762评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,329评论 0 329
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,678评论 1 270
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,583评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 47,995评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,493评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,145评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,293评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,250评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,267评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,973评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,556评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,648评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,873评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,257评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,809评论 2 339

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,975评论 4 60
  • 我曾经问过你一个问题,如果有些记忆潜居在碎隙中,记又记不起,忘又忘不掉,游离在黑白之间的边缘地带,那么那些记忆存在...
    Am_or阅读 289评论 0 0
  • 我经营着一家小广告公司,我的公司离家有两点几公里,每天我都要准时到公司。 有一阵子我常常走着去,每天早早的起床,吃...
    新意燕儿阅读 243评论 3 1
  • 陈道明有个广告:有人说,这个角色没有人比你演的更好了!那么,如果我再演一遍呢? 我们一直说,这世上没有最好,只有更...
    宵汀阅读 535评论 8 11