常用代码集合

0. NSLog的调试
#ifdef __OBJC__

#ifdef DEBUG
#define NSLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)
#else
#define NSLog(...)
#endif

#endif
1. 退回输入键盘
- (BOOL) textFieldShouldReturn:(id)textField{ [textField resignFirstResponder];
}
2. CGRect
frame = CGRectMake (origin.x, origin.y, size.width, size.height);矩形 
NSStringFromCGRect(someCG) 把 CGRect 结构转变为格式化字符串; 
CGRectFromString(aString) 由字符串恢复出矩形;
CGRectInset(aRect) 创建较小或较大的矩形(中心点相同),+较小 -较大 
CGRectIntersectsRect(rect1, rect2) 判断两矩形是否交叉,是否重叠 
CGRectZero 高度和宽度为零的/位于(0,0)的矩形常量
3. CGPoint & CGSize
CGPoint aPoint = CGPointMake(x, y); 
CGSize aSize = CGSizeMake(width, height);
4. 设置透明度
[myView setAlpha:value]; (0.0 < value < 1.0)
5. 自定义颜色
UIColor *newColor = [[UIColor alloc] initWithRed:(float) green:(float) blue:(float) alpha:(float)];
0.0~1.0 
6. 屏幕
竖屏: 320X480

横屏: 480X320

横屏:  [[UIApplication shareApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight].

屏幕变动检测: orientation == UIInterfaceOrientationLandscapeLeft
7. 隐藏状态栏
[[UIApplication shareApplication] setStatusBarHidden: YES
animated:NO]
8. 自动适应父视图大小:
aView.autoresizingSubviews = YES;
aView.autoresizingMask = (UIViewAutoresizingFlexibleWidth |
                          UIViewAutoresizingFlexibleHeight);
9. 图片压缩

压缩图片

用法:UIImage *yourImage= [self imageWithImageSimple:image scaledToSize:CGSizeMake(210.0, 210.0)];

压缩图片
- (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
    Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    Tell the old image to draw in this newcontext, with the desired
    new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    End the context
    UIGraphicsEndImageContext();
    Return the new image.
    return newImage;
}
10. 对图库的操作
  • 1, 选择相册:
UIImagePickerControllerSourceTypesourceType=UIImagePickerControllerSourceTypeCamera;
    if (![UIImagePickerControllerisSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
    }
    UIImagePickerController * picker = [[UIImagePickerControlleralloc]init];
    picker.delegate = self;
    picker.allowsEditing=YES;
    picker.sourceType=sourceType;
    [self presentModalViewController:picker animated:YES];
  • 2, 选择完毕:
    -(void)imagePickerController:(UIImagePickerController*)pickerdidFinishPickingMediaWithInfo:(NSDictionary *)info
    {
        [picker dismissModalViewControllerAnimated:YES];
        UIImage * image=[info objectForKey:UIImagePickerControllerEditedImage];
        [self performSelector:@selector(selectPic:) withObject:imageafterDelay:0.1];
    }
    -(void)selectPic:(UIImage*)image
    {
        NSLog(@"image%@",image);
        imageView = [[UIImageView alloc] initWithImage:image];
        imageView.frame = CGRectMake(0, 0, image.size.width, image.size.height);
        [self.viewaddSubview:imageView];
        [self performSelectorInBackground:@selector(detect:) withObject:nil];
    }

-3, 取消选择:

 -(void)imagePickerControllerDIdCancel:(UIImagePickerController*)picker
    {
        [picker dismissModalViewControllerAnimated:YES];
    }
11. Status Bar操作
隐藏Status Bar
[[UIApplication sharedApplication]setStatusBarHidden:YES animated:NO];

 状态栏的网络活动风火轮是否旋转
  [UIApplication sharedApplication].networkActivityIndicatorVisible,默认值是NO。
12. 键盘透明
    textField.keyboardAppearance = UIKeyboardAppearanceAlert; 
13. 截取屏幕图片

创建一个基于位图的图形上下文并指定大小为

    CGSizeMake(200,400)
    
    UIGraphicsBeginImageContext(CGSizeMake(200,400));
    renderInContext 呈现接受者及其子范围到指定的上下文
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    返回一个基于当前图形上下文的图片
    UIImage *aImage = UIGraphicsGetImageFromCurrentImageContext();
    移除栈顶的基于当前位图的图形上下文
    UIGraphicsEndImageContext();
    以png格式返回指定图片的数据
    imageData = UIImagePNGRepresentation(aImage);
14. 修改PlaceHolder的默认颜色
[username_text setValue:[UIColor colorWithRed:1 green:1 blue:1 alpha:0.5] forKeyPath:@"_placeholderLabel.textColor"];
15. 页面上移解决文本框被键盘弹出挡住的问题
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [username_text resignFirstResponder];
    [password_text resignFirstResponder];
    When the user presses return, take focus away from the text field so that the keyboard is dismissed.
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    CGRect rect = CGRectMake(0.0f, 0.0f, self.view.frame.size.width, self.view.frame.size.height);
    self.view.frame = rect;
    [UIView commitAnimations];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    When the user presses return, take focus away from the text field so that the keyboard is dismissed.
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    CGRect rect = CGRectMake(0.0f, 0.0f, self.view.frame.size.width, self.view.frame.size.height);
    self.view.frame = rect;
    [UIView commitAnimations];
    [textField resignFirstResponder];
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    CGRect frame = password_text.frame;
    int offset = frame.origin.y + 32 - (self.view.frame.size.height - 216.0);//键盘高度216
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyBoard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    float width = self.view.frame.size.width;
    float height = self.view.frame.size.height;
    if(offset > 0)
    {
        CGRect rect = CGRectMake(0.0f, -offset,width,height);
        self.view.frame = rect;
    }
    [UIView commitAnimations];
}

16. iOS代码加密常用加密方式
  • 1, MD5加密
.h中
#import <Foundation/Foundation.h>
@interface CJMD5 : NSObject

+(NSString *)md5HexDigest:(NSString *)input;

@end

-------------------------------------------
.m中

#import "CJMD5.h"
#import <CommonCrypto/CommonDigest.h>

@implementation CJMD5

+(NSString *)md5HexDigest:(NSString *)input{
    const char* str = [input UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, strlen(str), result);
    NSMutableString *ret = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH];
    for(int i = 0; i<CC_MD5_DIGEST_LENGTH; i++) {
        [ret appendFormat:@"%02X",result];
    }
    return ret;
}
@end

----------------------------------------------------------------
MD5是不可逆的只有加密没有解密,iOS代码加密使用方式如下
NSString *userName = @"cerastes";
NSString *password = @"hello Word";

MD5加密
NSString *md5 = [CJMD5 md5HexDigest:password];

NSLog(@"%@",md5);
END

  • 2, AES加密
NSString *encryptedData = [AESCrypt encrypt:userName password:password];加密

NSString *message = [AESCrypt decrypt:encryptedData password:password]; 解密

NSLog(@"加密结果 = %@",encryptedData);

NSLog(@"解密结果 = %@",message);
  • 3, BASE64加密iOS代码加密

.h

+ (NSString*)encodeBase64String:(NSString *)input;

+ (NSString*)decodeBase64String:(NSString *)input;

+ (NSString*)encodeBase64Data:(NSData *)data;

+ (NSString*)decodeBase64Data:(NSData *)data;


.m

+ (NSString*)encodeBase64String:(NSString * )input {
    
    NSData *data = [input dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    
    data = [GTMBase64 encodeData:data];
    
    NSString *base64String = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    return base64String;
    
}


+ (NSString*)decodeBase64String:(NSString * )input {
    
    NSData *data = [input dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    data = [GTMBase64 decodeData:data];
    NSString *base64String = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return base64String;
}

// 加密
+ (NSString*)encodeBase64Data:(NSData *)data {
    data = [GTMBase64 encodeData:data];
    NSString *base64String = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return base64String;
}

// 加密
+ (NSString*)decodeBase64Data:(NSData *)data {
    data = [GTMBase64 decodeData:data];
    
    NSString *base64String = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    return base64String;
    
}


BASE64加密
NSString *baseEncodeString = [GTMBase64 encodeBase64String:password];

NSString *baseDecodeString = [GTMBase64 decodeBase64String:baseEncodeString];

NSLog(@"baseEncodeString = %@",baseEncodeString);

NSLog(@"baseDecodeString = %@",baseDecodeString);
17. 版本比较
+ (BOOL)isVersion:(NSString*)versionA biggerThanVersion:(NSString*)versionB
{
    NSArray *arrayNow = [versionB componentsSeparatedByString:@"."];
    NSArray *arrayNew = [versionA componentsSeparatedByString:@"."];
    BOOL isBigger = NO;
    NSInteger i = arrayNew.count > arrayNow.count? arrayNow.count : arrayNew.count;
    NSInteger j = 0;
    BOOL hasResult = NO;
    for (j = 0; j < i; j ++) {
        NSString* strNew = [arrayNew objectAtIndex:j];
        NSString* strNow = [arrayNow objectAtIndex:j];
        if ([strNew integerValue] > [strNow integerValue]) {
            hasResult = YES;
            isBigger = YES;
            break;
        }
        if ([strNew integerValue] < [strNow integerValue]) {
            hasResult = YES;
            isBigger = NO;
            break;
        }
    }
    if (!hasResult) {
        if (arrayNew.count > arrayNow.count) {
            NSInteger nTmp = 0;
            NSInteger k = 0;
            for (k = arrayNow.count; k < arrayNew.count; k++) {
                nTmp += [[arrayNew objectAtIndex:k]integerValue];
            }
            if (nTmp > 0) {
                isBigger = YES;
            }
        }
    }
    return isBigger;
}
18. setValue: forKey:的定义
@interface NSMutableDictionary(NSKeyValueCoding)
/* Send -setObject:forKey: to the receiver, unless the value is nil, in which case send -removeObject:forKey:.
*/
- (void)setValue:(id)value forKey:(NSString *)key;

@end
value 为 nil ,调用 removeObject:forKey:
value不为nil时调用 setObject:forKey:
key为NSString类型。

2 setObject:forKey:的定义

@interface NSMutableDictionary : NSDictionary
- (void)removeObjectForKey:(id)aKey;
- (void)setObject:(id)anObject forKey:(id <NSCopying>)aKey;
@end


anobject不能为nil,而且key是一个id类型,不仅限于NSString类型

两者的区别:

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

推荐阅读更多精彩内容