iOS常用的封裝方法

做開發也有一段時間了,看了好多大神的代碼,總體感覺他們寫的代碼簡潔,好看,然而在對比下我寫的代碼,混亂,無序,簡直不堪入目啊!? ? ? ? ? ? ? ? 總體來說大神們的代碼封裝的都比較好,對一個項目要重復用到的代碼他們都會封裝起來,這樣用起來的時候也比較方便,也不用重復的去寫這段代碼了!? ? ? ? ? ? ? 下面是我在開發中封裝到的一些經常使用的一些方法,如有寫錯的地方或者大家有更好的方法,還請大家給我提出來,大家一起學習!謝謝!

?1.常用控件方法的封裝:

?#import

#import@interface MyUtil : NSObject?

//創建標簽的方法

+ (UILabel *)createLabelFrame:(CGRect)frame text:(NSString *)text textColor:(UIColor *)textColor textAlignment:(NSTextAlignment)textAlignment numberOfLines:(NSInteger)numberOfLines;

?+ (UILabel *)createLabelFrame:(CGRect)frame text:(NSString *)text color:(UIColor *)textColor;

?//創建按鈕的方法

+ (UIButton *)createBtnFrame:(CGRect)frame title:(NSString *)title bgImageName:(NSString *)bgImageName target:(id)target action:(SEL)action; //創建圖片視圖的方法+ (UIImageView *)createImageViewFrame:(CGRect)frame imageName:(NSString *)imageName;?

//類型的英文轉化成中文

+ (NSString *)transferCateName:(NSString *)name;?

@end 方法的實現:

? #import"MyUtil.h"?

@implementation MyUtil?

+(UILabel *)createLabelFrame:(CGRect)frame text:(NSString *)text textColor:(UIColor *)textColor textAlignment:(NSTextAlignment)textAlignment numberOfLines:(NSInteger)numberOfLines{? ?

?UILabel *label = [[UILabelalloc] initWithFrame:frame];? ? label.text = text;? ? label.textAlignment = textAlignment;? ? label.textColor = textColor;? ? label.numberOfLines = numberOfLines;? ??

? ? return label;

}?

+(UILabel *)createLabelFrame:(CGRect)frame text:(NSString *)text color:(UIColor *)textColor{? ? return [selfcreateLabelFrame:frame text:texttextColor:textColortextAlignment:NSTextAlignmentCenternumberOfLines:1];

}?

+(UIButton *)createBtnFrame:(CGRect)frame title:(NSString *)title bgImageName:(NSString *)bgImageName target:(id)target action:(SEL)action{??

? UIButton *btn = [UIButtonbuttonWithType:UIButtonTypeCustom];??

? btn.frame = frame;??

? [btnsetTitle:title forState:UIControlStateNormal];? ?

?[btnsetTitleColor:[UIColorblackColor] forState:UIControlStateNormal];? ? [btnsetBackgroundImage:[UIImageimageNamed:bgImageName] forState:UIControlStateNormal];??

? [btnaddTarget:target action:actionforControlEvents:UIControlEventTouchUpInside];? ? return ban;

}?

+(UIImageView *)createImageViewFrame:(CGRect)frame imageName:(NSString *)imageName{??

? UIImageView *imageView = [[UIImageViewalloc] initWithFrame:frame];? ? imageView.image = [UIImageimageNamed:imageName];??

? return imageView;

}??

+ (NSString *)transferCateName:(NSString *)name{? ?

?? ? if ([name isEqualToString:@"Business"]) {? ??

? return @"商業";??

? }elseif ([name isEqualToString:@"Weather"]) {? ??

? return @"天氣";? ?

?}elseif ([name isEqualToString:@"Tool"]) {?

?? ? return @"工具";? ?

?}elseif ([name isEqualToString:@"Travel"]) {? ?

?? return @"旅行";??

? }elseif ([name isEqualToString:@"Sports"]) {? ?

?? return @"體育";

? ? }elseif ([name isEqualToString:@"Social"]) {? ??

? return @"社交";? ? }elseif ([name isEqualToString:@"Refer"]) {?

?? ? return @"參考";??

? }elseif ([name isEqualToString:@"Ability"]) {??

? ? return @"效率";? ? }elseif ([name isEqualToString:@"Photography"]) {? ?

?? return @"攝影";? ? }elseif ([name isEqualToString:@"News"]) {? ??

? return @"新聞";? ? }elseif ([name isEqualToString:@"Gps"]) {? ??

? return @"導航";? ? }elseif ([name isEqualToString:@"Music"]) {? ??

? return @"音樂";? ? }elseif ([name isEqualToString:@"Life"]) {? ?

?? return @"生活";? ? }elseif ([name isEqualToString:@"Health"]) {?

?? ? return @"健康";? ? }elseif ([name isEqualToString:@"Finance"]) {?

?? ? return @"財務";? ? }elseif ([name isEqualToString:@"Pastime"]) {??

? ? return @"娛樂";? ? }elseif ([name isEqualToString:@"Education"]) {??

? ? return @"教育";? ? }elseif ([name isEqualToString:@"Book"]) {??

? ? return @"書籍";? ? }elseif ([name isEqualToString:@"Medical"]) {??

? ? return @"醫療";? ? }elseif ([name isEqualToString:@"Catalogs"]) {?

?? ? return @"商品指南";? ? }elseif ([name isEqualToString:@"FoodDrink"]) {

? ? ? return @"美食";? ? }elseif ([name isEqualToString:@"Game"]) {? ?

?? return @"游戲";? ? }elseif([name isEqualToString:@"All"]){? ?

?? return @"全部";? ?

?}? ? ?

?? return nil;

}?

@end??

2.裁剪圖片方法的封裝:

?- (UIImage*)clipImage:(UIImage*)bigImage inRect:(CGRect)rect{?

?CGImageRef imageRef =CGImageCreateWithImageInRect(bigImage.CGImage, rect);? UIImage *image = [UIImageimageWithCGImage:imageRef];? return image;

}?

實現方法: ? ? ? ? ? ??

?//創建圖片顯示?

?? ? ? ? ? CGRect frame =CGRectMake(100*j,100*i, 100,100);? ? ?

?? ? ? UIImage *tmpImage = [selfclipImage:image inRect:frame];??

3.封裝的下載方法:

?#import@classMyDownloader;@protocol MyDownloaderDelegate- (void)downloadFail:(MyDownloader *)downloader error:(NSError *)error;- (void)downloadFinish:(MyDownloader *)downloader;

?@end

?@interface MyDownloader :NSObject- (void)downloadWithURLString:(NSString *)urlString;?

@property (nonatomic,readonly)NSData *receiveData;@property (nonatomic,assign)NSInteger type;?

@property (nonatomic,weak)iddelegate;?

@end 實現方法:

?#import "MyDownloader.h"

?@implementation MyDownloader{??

? NSURLConnection *_conn;? ??

NSMutableData *_receiveData;

} -(instancetype)init{??

? self = [superinit];? ?

?if (self) {? ? ??

? _receiveData = [NSMutableDatadata];

? ? }? ? ??

? returnself;} -(void)downloadWithURLString:(NSString *)urlString{??

? NSURL *url = [NSURLURLWithString:urlString];? ?

?NSURLRequest *request = [NSURLRequestrequestWithURL:url];?

?? _conn = [NSURLConnectionconnectionWithRequest:request delegate:self];} #pragma mark - NSURLConnection代理-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{? ? [self.delegatedownloadFail:selferror:error];} -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{? ? [_receiveDatasetLength:0];} -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{? ? [_receiveDataappendData:data];} -(void)connectionDidFinishLoading:(NSURLConnection *)connection{? ? [self.delegatedownloadFinish:self];}? 4.block封裝的下載方法: #importtypedefvoid (^FINISHBLOCK)(NSData *receiveData);typedefvoid (^FAILBLOCK)(NSError *error);? @interface MyDownloader :NSObject{? ? NSMutableData *_receiveData;? ? ? ? NSURLConnection *_conn;? ? ? ? //下載成功結束? ? //void (^_myFinishBlock)(NSData *data);? ? ? ? FINISHBLOCK _myFinishBlock;? ? ? ? //下載失敗時調用? ? //void (^_myFailBlock)(NSError *error);? ? FAILBLOCK _myFailBlock;? ? } //下載的方法/* @param urlString:下載的字符串鏈接 @param finishBlock:下載成功時調用的代碼塊 @param failBlock:下載失敗時調用的代碼塊 *//*- (void)downloadWithURLString:(NSString *)urlString? ? ? ? ? ? ? ? ? ? ? finish:(void (^) (NSData *receiveData))finishBlock? ? ? ? ? ? ? ? ? ? ? ? fail:(void (^)(NSError *error))failBlock; */- (void)downloadWithURLString:(NSString *)urlString? ? ? ? ? ? ? ? ? ? ? finish:(FINISHBLOCK)finishBlock? ? ? ? ? ? ? ? ? ? ? ? fail:(FAILBLOCK)failBlock;? @end? 實現方法: #import "MyDownloader.h" @implementation MyDownloader -(instancetype)init{? ? if (self = [superinit]) {? ? ? ? _receiveData = [NSMutableDatadata];? ? }? ? returnself;}? -(void)downloadWithURLString:(NSString *)urlString finish:(void (^)(NSData *))finishBlock fail:(void (^)(NSError *))failBlock{? ? if (_myFinishBlock != finishBlock) {? ? ? ? _myFinishBlock = finishBlock;? ? }? ? ? ? if (_myFailBlock != failBlock) {? ? ? ? _myFailBlock = failBlock;? ? }? ? ? ? //下載? ? NSURL *url = [NSURLURLWithString:urlString];? ? ? ? NSURLRequest *request = [NSURLRequestrequestWithURL:url];? ? ? ? _conn = [NSURLConnectionconnectionWithRequest:request delegate:self];} #pragma mark - NSURLConnection代理-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{? ? if (_myFailBlock) {? ? ? ? _myFailBlock(error);? ? }} -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{? ? [_receiveDatasetLength:0];} -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{? ? [_receiveDataappendData:data];} -(void)connectionDidFinishLoading:(NSURLConnection *)connection{? ? if (_myFinishBlock) {? ? ? ? _myFinishBlock(_receiveData);? ? }} @end5.數據庫的封裝: #import#import "UserModel.h"

@interface DBManager :NSObject

+ (DBManager *)sharedManager;

//增

- (void)addUserModel:(UserModel *)model;

//刪

- (void)deleteUserWithUserId:(int)userId;

//改

//根據userId修改數據(userId是不變化的)

- (void)updateUserModel:(UserModel *)model userId:(int)userId;

//查

- (NSArray *)searchAllUsers;

@end

實現方法:

#import "DBManager.h"

#import "FMDatabase.h"

/*

使用數據庫時

1.導入fmdatabase第三方庫

2.導入系統libsqlite3.dylib

3.fmdatabase不支持ARC,五個.m文件添加-fno-objc-arc

*/

@implementation DBManager

{

//數據庫文件的關聯對象

FMDatabase *_dataBase;

}

+(DBManager *)sharedManager

{

staticDBManager *manager = nil;

@synchronized(self){

if (manager ==nil) {

manager = [[DBManageralloc] init];

}

}

return manager;

}

-(instancetype)init

{

if (self = [superinit]) {

//創建數據庫文件操作對象

[selfcreateDatabase];

}

returnself;

}

- (void)createDatabase

{

//數據庫文件的路徑

NSString *path = [NSHomeDirectory()stringByAppendingPathComponent:@"Documents/user.sqlite"];

NSLog(@"%@",path);

//1、初始化FMDataBase對象

_dataBase = [[FMDatabasealloc] initWithPath:path];

//2、打開數據庫

BOOL isOpen = [_dataBaseopen];

if (isOpen) {

//3、創建表格

//NSData -> blob

//int -> integer

//NSString -> varchar(255)

//if not exists:如果表格不存在,創建表格

//存在就不創建

//主鍵:primary key,值唯一,不能重復

//主鍵自動增長:autoincrement

NSString *createSql =@"create table if not exists user (userId integer primary key autoincrement, userName varchar(255), age integer,headImage blob)";

BOOL ret = [_dataBaseexecuteUpdate:createSql];

if (ret) {

NSLog(@"表格創建成功");

}else{

NSLog(@"%@",_dataBase.lastErrorMessage);

}

}else{

NSLog(@"數據庫打開失敗");

}

}

//判斷是否存在

- (BOOL)isExists:(NSString *)userName

{

NSString *sql =@"select * from user where userName = ?";

FMResultSet *rs = [_dataBaseexecuteQuery:sql, userName];

if ([rsnext]) {

returnYES;

}

returnNO;

}

//增加一條記錄

-(void)addUserModel:(UserModel *)model

{

//判斷用戶名是否存在

BOOL isExists = [selfisExists:model.userName];

if (isExists) {

NSLog(@"用戶名已存在");

return;

}

//?是占位符,表示要傳一個值

NSString *insertSql =@"insert into user (userName, age, headImage) values (?, ? ,?)";

//圖片轉換成二進制

NSData *imageData =UIImagePNGRepresentation(model.headImage);

BOOL ret = [_dataBaseexecuteUpdate:insertSql,model.userName,@(model.age), imageData];

if (!ret) {

NSLog(@"%@",_dataBase.lastErrorMessage);

}

}

//查詢

-(NSArray *)searchAllUsers

{

NSString *selectSql =@"select * from user";

FMResultSet *rs = [_dataBaseexecuteQuery:selectSql];

NSMutableArray *array = [NSMutableArrayarray];

while ([rsnext]) {

UserModel *model = [[UserModelalloc] init];

model.userId = [rsintForColumn:@"userId"];

model.userName = [rsstringForColumn:@"userName"];

model.age = [rsintForColumn:@"age"];

NSData *data = [rsdataForColumn:@"headImage"];

model.headImage = [UIImageimageWithData:data];

[array addObject:model];

}

return array;

}

//刪除

-(void)deleteUserWithUserId:(int)userId

{

NSString *deleteSql =@"delete from user where userId=?";

BOOL ret = [_dataBaseexecuteUpdate:deleteSql, @(userId)];

if (!ret) {

NSLog(@"%@",_dataBase.lastErrorMessage);

}

}

//修改

-(void)updateUserModel:(UserModel *)model userId:(int)userId

{

NSString *sql =@"update user set userName=?, age=?, headImage=? where userId=?";

//圖片轉換成二進制數據

NSData *data =UIImagePNGRepresentation(model.headImage);

BOOL ret = [_dataBaseexecuteUpdate:sql, model.userName,@(model.age), data,@(userId)];

if (!ret) {

NSLog(@"%@",_dataBase.lastErrorMessage);

}

}

@end

6.UIAlertController的封裝方法:

- (void)createAlertViewText:(NSString *)text

{

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"溫馨提示" message:text preferredStyle:UIAlertControllerStyleAlert];

UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

}];

UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

}];

[alertController addAction:okAction];

[alertController addAction:cancelAction];

[self presentViewController:alertController animated:YES completion:nil];

}

實現方法:

- (void)searchBtnClick

{

[_licenseNumber resignFirstResponder];

_dp.hidden = YES;

_lineView.hidden = YES;

_endBtn.hidden = YES;

_showOrHidden = YES;

NSMutableArray *licens = ((AppDelegate *)[UIApplication sharedApplication].delegate).licen;

for (int i=0; i

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容