iOS 简单控件封装

近来无事就把项目中有关封装玩意儿整理一下。话不多说直接上菜。

UIButton 简单封装

UIButton 属性很多所以很多都不敢写进去怕啰嗦 剩下的大家可以根据自己的需求进行添加(以下控件不在多说)。

+(UIButton*)CreateUIButtonWithButtonTitle:(NSString*)title buttonFrame:(CGRect)rect  UIFont:(CGFloat)titleSize titleColor:(UIColor*)titleColor buttonAction:(SEL)buttonAction superView:(UIView*)superView

其他属性可自行添加

+(UIButton*)CreateUIButtonWithButtonTitle:(NSString*)title buttonFrame:(CGRect)rect  UIFont:(CGFloat)titleSize titleColor:(UIColor*)titleColor buttonAction:(SEL)buttonAction superView:(UIView*)superView{
    
    UIButton *button =[UIButton buttonWithType:UIButtonTypeCustom];
    
    [button setFrame:rect];
    
    [button setTitle:title forState:UIControlStateNormal];
    
    [button setTitleColor:titleColor forState:UIControlStateNormal];
    
    [button addTarget:nil action:buttonAction forControlEvents:UIControlEventTouchUpInside];
  
    [[button titleLabel] setFont:[UIFont systemFontOfSize:titleSize]];
    
    [superView addSubview:button];
    
    return button;

}

UILabel 控件封装

+(UILabel*)CreateUILabelWithLabelTitle:(NSString*)title labelFrame:(CGRect)rect BackgroundColor:(UIColor*)bageColor UIFont:(CGFloat)titleSize numberOfLine:(NSInteger)numberLine textAlignment:(NSTextAlignment)textAlignment superView:(UIView*)superView;

其他属性可自行添加

+(UILabel*)CreateUILabelWithLabelTitle:(NSString *)title labelFrame:(CGRect)rect BackgroundColor:(UIColor *)bageColor UIFont:(CGFloat)titleSize numberOfLine:(NSInteger)numberLine textAlignment:(NSTextAlignment)textAlignment superView:(UIView*)superView{
    
    UILabel *label =[[UILabel alloc] initWithFrame:rect];
    
    [label setText:title];
    
    [label setBackgroundColor:bageColor];
    
    [label setFont:[UIFont systemFontOfSize:titleSize]];
    
    [label setTextAlignment:textAlignment];
    
    [label setNumberOfLines:numberLine];
    
    [superView addSubview:label];
    
    return label;
}

UIAlertController 原生弹框封装

UIAlertControllerStyleAlert

+(void)showAlertControllerWithTitle:(NSString *)title Message:(NSString *)message AactionCancleTitle:(NSString *)cancleTitle ActionSureTitle:(NSString *)sureTitle cancleAction:(void (^)(UIAlertAction * action))cancleAction sureAction:(void (^)(UIAlertAction *action))sureAction Controller:(UIViewController *)controller;

多余信息可直接用nil填充

+(void)showAlertControllerWithTitle:(NSString *)title Message:(NSString *)message AactionCancleTitle:(NSString *)cancleTitle ActionSureTitle:(NSString *)sureTitle cancleAction:(void (^)(UIAlertAction * action))cancleAction sureAction:(void (^)(UIAlertAction * action))sureAction Controller:(UIViewController *)controller{
    
    UIAlertController *alert =[UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *CancleAction =[UIAlertAction actionWithTitle:cancleTitle style:UIAlertActionStyleCancel handler:cancleAction];
    
    UIAlertAction *SureAction =[UIAlertAction actionWithTitle:sureTitle style:UIAlertActionStyleDefault handler:sureAction];
    
    if (cancleTitle !=nil) {
        
        [alert addAction:CancleAction];
    }
    
    if (sureTitle !=nil) {
        
        [alert addAction:SureAction];
    }

    [controller presentViewController:alert animated:YES completion:nil];
    
    
}

UIAlertControllerStyleActionSheet

+(void)showActionSheetAlertControllerWithTitle:(NSString*)title Message:(NSString*)message AactionCancleTitle:(NSString*)cancleTitle cancleAction:(void (^)(UIAlertAction * action))cancleAction contentArrays:(NSArray*)contentArrays alertAction:(void (^)(UIAlertAction *action))action Controller:(UIViewController *)controller;
+(void)showActionSheetAlertControllerWithTitle:(NSString *)title Message:(NSString *)message AactionCancleTitle:(NSString *)cancleTitle cancleAction:(void (^)(UIAlertAction *))cancleAction contentArrays:(NSArray *)contentArrays alertAction:(void (^)(UIAlertAction *))action Controller:(UIViewController *)controller{
    
    UIAlertController *alertController =[UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleActionSheet];
    
    if (cancleTitle !=nil) {
        
        UIAlertAction *canclAction = [UIAlertAction actionWithTitle:cancleTitle style:UIAlertActionStyleCancel handler:cancleAction];
        
        [alertController addAction:canclAction];
    }
    
    if (contentArrays.count > 0) {
        
        for (int i = 0; i<contentArrays.count; i++) {
            
            UIAlertAction *Actions = [UIAlertAction actionWithTitle:contentArrays[i] style:UIAlertActionStyleDefault handler:action];
            
            [alertController addAction:Actions];
        }
    }
    
    
    [controller presentViewController:alertController animated:YES completion:nil];
}

AFNetworking 数据上传下载封装

上传文件

+(void)UploadFileWithURL:(NSString *)url image:(UIImage*)image parameters:(NSDictionary *)param Progress:(void (^)(NSProgress *  uploadProgress))progress complete:(void (^)(NSURLSessionDataTask * task, id responseObject))success failure:(void (^)(NSURLSessionDataTask * task, NSError * error))failure;
上传前应跟后台沟通一下。
+(void)UploadFileWithURL:(NSString *)url image:(UIImage*)image parameters:(NSDictionary *)param Progress:(void (^)(NSProgress *  uploadProgress))progress complete:(void (^)(NSURLSessionDataTask * task, id responseObject))success failure:(void (^)(NSURLSessionDataTask * task, NSError * error))failure{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.requestSerializer = [[AFJSONRequestSerializer alloc] init];
    
    manager.responseSerializer.acceptableContentTypes = nil;
    
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager POST:url parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        NSData *data = UIImagePNGRepresentation(image);
        /*
         在网络开发中,上传文件时,是文件不允许被覆盖,文件重名 可以在上传时使用当前的系统事件作为文件名
         */
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        
        formatter.dateFormat = @"yyyyMMddHHmmss";
        
        NSString *str = [formatter stringFromDate:[NSDate date]];
        
        NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
        
        /*
         1. 要上传的[二进制数据]
         2. 后台处理文件的[字段"file"]
         3. 要保存在服务器上的[文件名]
         4. 上传文件的[mimeType]
         */
        [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/png"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        /*
             int64_t totalUnitCount        需要下载文件的总大小
             int64_t completedUnitCount    当前已经下载的大小
         */
        
        NSLog(@"%f",1.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            /*
                回到主队列刷新UI
             */
        });
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"上传成功 %@", responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"上传失败 %@", error);
        
    }];
    
    
}

GET格式请求

+(void)GETrequestWithUrl:(NSString *)urlString parameters:(NSDictionary *)param Complete:(void (^)(NSData * data))success fail:(void (^)(NSError * error))failture;
+(void)GETrequestWithUrl:(NSString *)urlString parameters:(NSDictionary *)param Complete:(void (^)(NSData *))success fail:(void (^)(NSError *))failture
{
    
    AFHTTPSessionManager *manager =[AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    urlString =[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    
    [manager GET:urlString parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //调用success的block
        
        success(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        failture(error);
    }];
    
    
}

POST格式请求

+(void)POSTrequestWithUrl:(NSString *)urlString parameters:(NSDictionary *)param Complete:(void (^)(NSData * data))success fail:(void (^)(NSError * error))failture;
+(void)POSTrequestWithUrl:(NSString *)urlString parameters:(NSDictionary *)param Complete:(void (^)(NSData *))success fail:(void (^)(NSError *))failture
{
    
    AFHTTPSessionManager *manager =[AFHTTPSessionManager manager];
    urlString =[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"%@",urlString);
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [manager POST:urlString parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //调用success的block
        success(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        failture(error);
    }];
    
    
}

字符串判空

+(BOOL)StringisKong:(NSString*)string;
+(BOOL)StringisKONG:(NSString *)string {
    if (string) {
        
        if (string == nil){
            
            return YES;
            
        }else if (string == NULL){
            
            return YES;
            
        }else if ([string isEqual:[NSNull null]]) {
            
            return YES;
            
        }else if ([string isKindOfClass:[NSNull class]]){
            
            return YES;
            
        }else if ([string containsString:@"null"]){
            
            return YES;
            
        }else if ([string containsString:@"NULL"]){
            
            return YES;
            
        }else if ([string isEqualToString:@""]|| [string isEqualToString:@"(null)"]){
            
            return YES;
            
        }else if([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0){
            
            return YES;
        }else{
            
            return NO;
            
        }
        
    }else{
        
        return YES;
    }
    
}

时间戳转换不同格式的时间

+ (NSString*)fromTimeInterval:(NSString*)timerInterval fromType:(NSInteger)type;

根据项目需求自行修改

+ (NSString*)fromTimeInterval:(NSString*)timerInterval fromType:(NSInteger)type{
    
    NSTimeInterval time =[timerInterval doubleValue]/ 1000;
    NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:time];
    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    
    switch (type) {
        case 0:
        {
            [dateFormatter setDateFormat:@"YYYY.MM.dd"];
            
            break;
        }
        case 1:
        {
              [dateFormatter setDateFormat:@"YYYY.MM.dd HH:mm"];
            
            break;
        }
        case 2:
        {
            [dateFormatter setDateFormat:@"YYYY-MM-dd"];
            
            break;
        }
        case 3:
        {
             [dateFormatter setDateFormat:@"MM/dd HH:mm"];
            
            break;
        }
        case 4:
        {
              [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm"];
            
            break;
        }
        case 5:
        {
            [dateFormatter setDateFormat:@"MM.dd HH:mm"];
            
            break;
        }
        default:
            break;
    }
    
    return [dateFormatter stringFromDate: detaildate];
}

自定义标签

标签定制在项目中的需求越来越常见我自己特意封装了一个View 代码简洁、引用方便、不确定标签个数的时候可以计算View 高度、支持单选和多选。

@interface CustomLabelView : UIView

@property (nonatomic,copy ) void (^ReturnSelectLabelTitles)(NSArray*labelTitlesArray);
@property(nonatomic ,copy ) void (^HeightDidChange)(CGFloat viewHeight);
- (instancetype)initWithTitles:(NSArray*)titles  isSelectMore:(BOOL)isSelectMore;

@end
static int lineNumbers ;//换行次数
static int selectIndex ;//当前选中的ButtonTag值

#define BTAG       2017527
#define LabelSpace 15
#define SpaceTop   15
#define SWIDTH [UIScreen mainScreen].bounds.size.width
#define SHEIGHT [UIScreen mainScreen].bounds.size.height
#define UIColorFromHex(s) [UIColor colorWithRed:(((s & 0xFF0000) >> 16))/255.0 green:(((s &0x00FF00) >>8))/255.0 blue:((s &0x0000FF))/255.0 alpha:1.0]

@interface CustomLabelView ()

@property(nonatomic, assign ) BOOL isSelectMore;
@property(nonatomic, strong ) NSMutableArray *selectIndexs;//选中的标签
@property(nonatomic, strong ) NSMutableArray *selectTitls;//选中的标签

@property(nonatomic, strong ) NSArray *labelTitles;//标签内容

@end

@implementation CustomLabelView


- (instancetype)initWithTitles:(NSArray *)titles isSelectMore:(BOOL)isSelectMore {
    
    if (self = [super init]) {
       
        if (titles.count > 0) {
            
            _isSelectMore = isSelectMore;
            
            _labelTitles = [NSArray arrayWithArray:titles];
            
            _selectTitls = [NSMutableArray arrayWithCapacity:0];
            _selectIndexs = [NSMutableArray arrayWithCapacity:0];
            
            CGFloat Current_H  = SpaceTop ;
            
            CGFloat Current_W  = 0.f ;
            
            for (int i = 0 ; i < titles.count; i++) {
                
                CGFloat LabelWidth = [titles[i] boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13]} context:nil].size.width + 20;
                
                if (Current_W + LabelWidth > SWIDTH) {
                    
                    Current_W = 0;
                    
                    Current_H = SpaceTop + 30*(lineNumbers +1);
                    
                    lineNumbers += 1;
                    
                }
                
                Current_W += LabelSpace  ;
                
                UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
                
                button.backgroundColor = UIColorFromHex(0xF8F8F8);
                button.tag = BTAG + i ;
                button.frame = CGRectMake(Current_W, Current_H, LabelWidth, 18);
                
                [button setTitle:titles[i] forState:UIControlStateNormal];
                
                [button setTitleColor:UIColorFromHex(0x969696) forState:UIControlStateNormal];
                
                button.titleLabel.font = [UIFont systemFontOfSize:13];
                Current_W = CGRectGetMaxX(button.frame);
                
                button.clipsToBounds = YES;
                
                button.layer.cornerRadius = 3;
                
                [button addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
                
                [self addSubview:button];
                
            }
   
        
        }
        
    }
    
    return self;
    
}
- (void)clickBtn:(UIButton*)selectButton{
    
    if (_isSelectMore) {

         selectIndex = (int)selectButton.tag - BTAG ;
        
        if ([_selectIndexs containsObject:@(selectIndex)]) {
            
            selectButton.backgroundColor = UIColorFromHex(0xF8F8F8);
            
            [_selectIndexs removeObject:@(selectIndex)];
            [_selectTitls removeObject:_labelTitles[selectIndex]];
            
            
        }else{
            
            selectButton.backgroundColor = UIColorFromHex(0xFF4C4D);
            
            [_selectIndexs addObject:@(selectIndex)];
            [_selectTitls addObject:_labelTitles[selectIndex]];
            
        }
    
        if (self.ReturnSelectLabelTitles) {
            
            self.ReturnSelectLabelTitles(_selectTitls);
            
        }
       
        
    }else{
        
        
        UIButton * button = [self viewWithTag:selectIndex];
        
        button.backgroundColor = UIColorFromHex(0xF8F8F8);
        
        selectIndex = selectIndex == selectButton.tag ? 0 : (int)selectButton.tag ;
        
        if (selectIndex > 0) {
            
            selectButton.backgroundColor = UIColorFromHex(0xFF4C4D);
            self.backgroundColor = [UIColor whiteColor];
            
            if (self.ReturnSelectLabelTitles) {
                
                self.ReturnSelectLabelTitles(@[selectButton.titleLabel.text]);
                
            }
            
            
        }

        
    }
    
    
}

简单引用

CustomLabelView *labelView = [[ CustomLabelView alloc] initWithTitles:titles isSelectMore:NO];
    
    labelView.frame = CGRectMake( 0, 100, self.view.frame.size.width, lineNumbers*35 );
   
    labelView.ReturnSelectLabelTitles = ^(NSArray * labelTitles){
        
        NSLog(@"%@",labelTitles);
    };
   
    [self.view addSubview:labelView];
    

计算高度

NSArray *titles = @[@"语文书",@"小马是个大逗逼",@"端午节快乐",@"我与僵尸有个约会DVD版",@"说好的。。。呢",@"干什么啊",@"智商堪忧",@"逗逼",@"我们要去旅游去了你去吗",@"我不去你去吧",@"哎真是的",@"你说啊为什么啊",@"不去拉倒",@"真是的"];
    /**
     *  计算 不固定Titles 高度 如果titles 固定可直接填写高度。
     */
    CGFloat Current_W  = 0.f ;
    for (int i = 0; i < titles.count; i++) {
        
        CGFloat LabelWidth = [titles[i] boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13]} context:nil].size.width + 20;
        
        if (Current_W + LabelWidth > self.view.frame.size.width) {
            
    
            lineNumbers += 1;
            
            Current_W = 0.f;
            
        }
    
         Current_W += LabelWidth + 15;

        NSLog(@"%d",lineNumbers);
        
    }

Demo下载地址: https://github.com/DearWang/customLabel

未完待续。。。

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

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 172,081评论 25 707
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,095评论 4 62
  • 长相思 情深意重 词 轻风拂柳 (一) 独倚栏,久倚栏, 约定归期人未还, 谁怜她影单? 月夜寒,寂夜寒, 媛女无...
    轻风拂柳阅读 753评论 27 46
  • 感情的开始就是一颗沙粒进入贝壳的开始,经过长时间的磨合,沙粒才有可能成为一粒珍珠,叫做幸福。
    说好的明天阅读 142评论 0 0
  • Mark1:终于,花花朝着自主阅读迈出了一大步。今天,自己拿着《笃笃笃》就指读了起来。妈妈偷偷听了一下,不认识的字...
    一花一世界_1412阅读 295评论 0 0