iOS常用的封装方法
做开发也有一段时间了,看了好多大神的代码,总体感觉他们写的代码简洁,好看,然而在对比下我写的代码,混乱,无序,简直不堪入目啊!
总体来说大神们的代码封装的都比较好,对一个项目要重复用到的代码他们都会封装起来,这样用起来的时候也比较方便,也不用重复的去写这段代码了!
下面是我在开发中封装到的一些经常使用的一些方法,如有写错的地方或者大家有更好的方法,还请大家给我提出来,大家一起学习!谢谢!
1.常用控件方法的封装:
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@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 btn;
}
+(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 <Foundation/Foundation.h>
@classMyDownloader;
@protocol MyDownloaderDelegate <NSObject>
- (void)downloadFail:(MyDownloader *)downloader error:(NSError *)error;
- (void)downloadFinish:(MyDownloader *)downloader;
@end
@interface MyDownloader :NSObject<NSURLConnectionDelegate,NSURLConnectionDataDelegate>
- (void)downloadWithURLString:(NSString *)urlString;
@property (nonatomic,readonly)NSData *receiveData;
@property (nonatomic,assign)NSInteger type;
@property (nonatomic,weak)id<MyDownloaderDelegate> delegate;
@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封装的下载方法:
#import <Foundation/Foundation.h>
typedefvoid (^FINISHBLOCK)(NSData *receiveData);
typedefvoid (^FAILBLOCK)(NSError *error);
@interface MyDownloader :NSObject<NSURLConnectionDataDelegate,NSURLConnectionDelegate>
{
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);
}
}
@end
5.数据库的封装:
#import <Foundation/Foundation.h>
#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<licens.count; i++) {
if ([_licenseNumber.text isEqualToString: licens[i]]) {
[self createData];
}
}
if ([_licenseNumber.text isEqual: @""])
{
[self createAlertViewText:@"车牌号不能为空"];
}
if ([_dateBtn.titleLabel.text isEqual: @"查询日期"])
{
[self createAlertViewText:@"请选择日期"];
}
}
iOS常用的封装方法的更多相关文章
- JavaScrpt常用的封装方法
1.闭包封装.在这个封装方法中,所有的实例成员都共享属性和方法, 使得所有得方法和属性都私有且对象间共享 (function ($) { var Person = function(name) { r ...
- iOS常用系统信息获取方法
一.手机电量获取,方法二需要导入头文件#import<objc/runtime.h> 方法一.获取电池电量(一般用百分数表示,大家自行处理就好) -(CGFloat)getBatteryQ ...
- iOS常用设计模式——工厂方法(简单工厂模式,工厂方法模式, 抽象工厂模式)
1. 简单工厂模式 如何理解简单工厂,工厂方法, 抽象工厂三种设计模式? 简单工厂方法包含:父类拥有共同基础接口,具体子类实现子类特殊功能,工厂类根据参数区分创建不同子类实例.该场景对应的UML图如下 ...
- 常用DBhelper封装方法
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threa ...
- web前端常用的封装方法
1.放大镜 //页面加载完毕后执行 window.onload = function () { var oDemo = document.getElementById('demo'); var oMa ...
- iOS常用加密方法(aes、md5、base64)
1.代码 iOS常用加密方法(aes.md5.base64) .AES加密 NSData+AES.h文件 // // NSData-AES.h // Smile // // Created by 周 ...
- iOS常用公共方法
iOS常用公共方法 字数2917 阅读3070 评论45 喜欢236 1. 获取磁盘总空间大小 //磁盘总空间 + (CGFloat)diskOfAllSizeMBytes{ CGFloat si ...
- iOS 常用公共方法
iOS常用公共方法 1. 获取磁盘总空间大小 //磁盘总空间 + (CGFloat)diskOfAllSizeMBytes{ CGFloat size = 0.0; NSError *error; N ...
- IOS常见的加密方法,常用的MD5和Base64
iOS代码加密常用加密方式 iOS代码加密常用加密方式,常见的iOS代码加密常用加密方式算法包括MD5加密.AES加密.BASE64加密,三大算法iOS代码加密是如何进行加密的,且看下文 MD5 iO ...
随机推荐
- CURL使用HTTPS的技术小结
摘自http://www.51testing.com/html/14/175414-248202.html CURL使用HTTPS的技术小结 cURL是linux下命令行提交HTTP(S)请求的一个很 ...
- C#初步接触
如同非常多刚開始学习的人一样,刚接触C#的时候,也是一头雾水,学习了好长时间,都搞不清楚一些基本名称是什么.什么是C#?什么是.net?什么是visual studio?它们之间有什么关系?以下我们就 ...
- Swift的初始化方法
我们在深入初始化方法之前,不妨先再想想Swift中的初始化想要达到一种怎样的目的. 其实就是安全.在Objective-C中,init方法是非常不安全的:没有人能保证init只被调用一次,也没有人保证 ...
- Javascript 中的false,零值,null,undefined和空字符串对象
在Javascript中,我们经常会接触到题目中提到的这5个比较特别的对象--false.0.空字符串.null和undefined.这几个对象很容易用错,因此在使用时必须得小心. 类型检测 我们下来 ...
- Net Configuration Assistant和Net Manager的区别
1.Net Configuration Assistant和Net Manager在oracle的配置工具中,Net Configuration Assistant(网络配置助手)和Net Manag ...
- Ubuntu 13.10 下安装node
1.首先更新Ubuntu在线包:sudo apt-get update && sudo apt-get dist-upgrade, 2.默认Ubuntu已经安装python的,具体版本 ...
- 把WCF服务部署服务器IIS异常(详细:处理程序“svc-Integrated”在其模块列表中有一个错误模块“ManagedPipelineHandler”)
详细:处理程序“svc-Integrated”在其模块列表中有一个错误模块“ManagedPipelineHandler” 原因: vs2010默认的是4.0框架,4.0的框架是独立的CLR,和2.0 ...
- ,gitignore 中规则不起作用的原因
.gitignore 文件的用途,该文件只能作用于 Untracked Files,也就是那些从来没有被 Git 记录过的文件(自添加以后,从未 add 及 commit 过的文件). 这样则好理解, ...
- Python爬虫实战(2):爬取京东商品列表
1,引言 在上一篇<Python爬虫实战:爬取Drupal论坛帖子列表>,爬取了一个用Drupal做的论坛,是静态页面,抓取比较容易,即使直接解析html源文件都可以抓取到需要的内容.相反 ...
- 算法分析-快速排序QUICK-SORT
设要排序的数组是A[0]……A[N-1],首先任意选取一个数据(通常选用数组的第一个数)作为关键数据,然后将所有比它小的数都放到它前面,所有比它大的数都放到它后面,这个过程称为一趟快速排序.值得注意的 ...