常用代码集合

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 
@interface CJMD5 : NSObject

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

@end

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

#import "CJMD5.h"
#import 

@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
  • 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 )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:的可以是任何类型
    待续...

你可能感兴趣的:(常用代码集合)