近来无事就把项目中有关封装玩意儿整理一下。话不多说直接上菜。
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
网友评论