iOS 簡單控件封裝

近來無事就把項(xiàng)目中有關(guān)封裝玩意兒整理一下。話不多說直接上菜。

UIButton 簡單封裝

UIButton 屬性很多所以很多都不敢寫進(jìn)去怕啰嗦 剩下的大家可以根據(jù)自己的需求進(jìn)行添加(以下控件不在多說)。

+(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 數(shù)據(jù)上傳下載封裝

上傳文件

+(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;
上傳前應(yīng)跟后臺(tái)溝通一下。
+(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);
        /*
         在網(wǎng)絡(luò)開發(fā)中,上傳文件時(shí),是文件不允許被覆蓋,文件重名 可以在上傳時(shí)使用當(dāng)前的系統(tǒng)事件作為文件名
         */
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        
        formatter.dateFormat = @"yyyyMMddHHmmss";
        
        NSString *str = [formatter stringFromDate:[NSDate date]];
        
        NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
        
        /*
         1. 要上傳的[二進(jìn)制數(shù)據(jù)]
         2. 后臺(tái)處理文件的[字段"file"]
         3. 要保存在服務(wù)器上的[文件名]
         4. 上傳文件的[mimeType]
         */
        [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/png"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        /*
             int64_t totalUnitCount        需要下載文件的總大小
             int64_t completedUnitCount    當(dāng)前已經(jīng)下載的大小
         */
        
        NSLog(@"%f",1.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            /*
                回到主隊(duì)列刷新UI
             */
        });
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"上傳成功 %@", responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"上傳失敗 %@", error);
        
    }];
    
    
}

GET格式請(qǐng)求

+(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) {
        //調(diào)用success的block
        
        success(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        failture(error);
    }];
    
    
}

POST格式請(qǐng)求

+(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) {
        
        //調(diào)用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;
    }
    
}

時(shí)間戳轉(zhuǎn)換不同格式的時(shí)間

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

根據(jù)項(xiàng)目需求自行修改

+ (NSString*)fromTimeInterval:(NSString*)timerInterval fromType:(NSInteger)type{
    
    NSTimeInterval time =[timerInterval doubleValue]/ 1000;
    NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:time];
    //實(shí)例化一個(gè)NSDateFormatter對(duì)象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //設(shè)定時(shí)間格式,這里可以設(shè)置成自己需要的格式
    
    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];
}

自定義標(biāo)簽

標(biāo)簽定制在項(xiàng)目中的需求越來越常見我自己特意封裝了一個(gè)View 代碼簡潔、引用方便、不確定標(biāo)簽個(gè)數(shù)的時(shí)候可以計(jì)算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 ;//換行次數(shù)
static int selectIndex ;//當(dāng)前選中的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;//選中的標(biāo)簽
@property(nonatomic, strong ) NSMutableArray *selectTitls;//選中的標(biāo)簽

@property(nonatomic, strong ) NSArray *labelTitles;//標(biāo)簽內(nèi)容

@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];
    

計(jì)算高度

NSArray *titles = @[@"語文書",@"小馬是個(gè)大逗逼",@"端午節(jié)快樂",@"我與僵尸有個(gè)約會(huì)DVD版",@"說好的。。。呢",@"干什么啊",@"智商堪憂",@"逗逼",@"我們要去旅游去了你去嗎",@"我不去你去吧",@"哎真是的",@"你說啊為什么啊",@"不去拉倒",@"真是的"];
    /**
     *  計(jì)算 不固定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

未完待續(xù)。。。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,872評(píng)論 25 709
  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,138評(píng)論 4 61
  • 長相思 情深意重 詞 輕風(fēng)拂柳 (一) 獨(dú)倚欄,久倚欄, 約定歸期人未還, 誰憐她影單? 月夜寒,寂夜寒, 媛女無...
    輕風(fēng)拂柳閱讀 814評(píng)論 27 46
  • 感情的開始就是一顆沙粒進(jìn)入貝殼的開始,經(jīng)過長時(shí)間的磨合,沙粒才有可能成為一粒珍珠,叫做幸福。
    說好的明天閱讀 204評(píng)論 0 0
  • Mark1:終于,花花朝著自主閱讀邁出了一大步。今天,自己拿著《篤篤篤》就指讀了起來。媽媽偷偷聽了一下,不認(rèn)識(shí)的字...
    一花一世界_1412閱讀 357評(píng)論 0 0

友情鏈接更多精彩內(nèi)容