iOS 日常记录

1.枚举

typedef enum : NSUInteger {
    HXPhotoModelMediaSubTypePhoto = 0,  //!< 照片
    HXPhotoModelMediaSubTypeVideo       //!< 视频
} HXPhotoModelMediaSubType;

2.TabBar跳转隐藏(继承UINavigationController)

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    if ([self.viewControllers count] > 0) {
        viewController.hidesBottomBarWhenPushed = YES;
    }
    [super pushViewController:viewController animated:animated];
}

3.扩大按钮的点击范围(继承UIButton)

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent*)event{
    //获取当前button的实际大小
    CGRect bounds = self.bounds;
    //若原热区小于44x44,则放大热区,否则保持原大小不变
    CGFloat widthDelta = MAX(44.0 - bounds.size.width, 0);
    CGFloat heightDelta = MAX(44.0 - bounds.size.height, 0);
    //扩大bounds
    bounds = CGRectInset(bounds, -0.5 * widthDelta, -0.5 * heightDelta);
    //如果点击的点 在 新的bounds里,就返回YES
    return CGRectContainsPoint(bounds, point);
}

4.字典转字符串

+ (NSString *)dicToJsonStr:(NSDictionary *)dic {
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:0 error:&error];
    if (!jsonData) {
        NSLog(@"Got an error: %@", error);
        return @"";
    }else {
        return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
}

5.数组转字符串

+ (NSString *)arrayToJsonStr:(NSArray *)array {
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted  error:&error];
    if (!jsonData) {
        NSLog(@"Got an error: %@", error);
        return @"";
    } else {
        return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
}

6.字符串转字典

+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    
    if (jsonString == nil) {
        return nil;
    }else{
        NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
        NSError *err;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
        if(err) {
            NSLog(@"json解析失败:%@",err);
            return nil;
        }
        return dic;
    }
}

7.获取uuid

+ (NSString *)uuid{
    // create a new UUID which you own
    CFUUIDRef uuidref = CFUUIDCreate(kCFAllocatorDefault);
    // create a new CFStringRef (toll-free bridged to NSString)
    // that you own
    CFStringRef uuid = CFUUIDCreateString(kCFAllocatorDefault, uuidref);
    NSString *result = (__bridge NSString *)uuid;
    //release the uuidref
    CFRelease(uuidref);
    // release the UUID
    CFRelease(uuid);
    return result;
}

8.设置点击手势部分响应

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    if ([touch.view isDescendantOfView:self.shopcarTableView]) {
        return NO;
    }
    return YES;
}

9.单例

+ (instancetype)sharedManager {
    static dispatch_once_t onceToken;
    static IPhoneCallManager *instance = nil;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] initInPrivate];
    });
    return instance;
}

10.十六进制字符串颜色

//color:支持@“#123456”、 @“0X123456”、 @“123456”三种格式
+ (UIColor *)colorWithHexString:(NSString *)color alpha:(CGFloat)alpha
{
    //删除字符串中的空格
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    // String should be 6 or 8 characters
    if ([cString length] < 6)
    {
        return [UIColor clearColor];
    }
    // strip 0X if it appears
    //如果是0x开头的,那么截取字符串,字符串从索引为2的位置开始,一直到末尾
    if ([cString hasPrefix:@"0X"])
    {
        cString = [cString substringFromIndex:2];
    }
    //如果是#开头的,那么截取字符串,字符串从索引为1的位置开始,一直到末尾
    if ([cString hasPrefix:@"#"])
    {
        cString = [cString substringFromIndex:1];
    }
    if ([cString length] != 6)
    {
        return [UIColor clearColor];
    }

    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    //r
    NSString *rString = [cString substringWithRange:range];
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];

    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    return [UIColor colorWithRed:((float)r / 255.0f) green:((float)g / 255.0f) blue:((float)b / 255.0f) alpha:alpha];
}

//默认alpha值为1
+ (UIColor *)colorWithHexString:(NSString *)color
{
    return [self colorWithHexString:color alpha:1.0f];
}

11.获取当前视图控制器

信息来源:http://blog.bombox.org/2016-05-11/find-current-viewcontroller/

/** 获取当前控制器 */
+(UIViewController *)currentVC
{
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    //当前windows的根控制器
    UIViewController *controller = window.rootViewController;
    //通过循环一层一层往下查找
    while (YES) {
        //先判断是否有present的控制器
        if (controller.presentedViewController) {
            //有的话直接拿到弹出控制器,省去多余的判断
            controller = controller.presentedViewController;
        } else {
            if ([controller isKindOfClass:[UINavigationController class]]) {
                //如果是NavigationController,取最后一个控制器(当前)
                controller = [controller.childViewControllers lastObject];
            } else if ([controller isKindOfClass:[UITabBarController class]]) {
                //如果TabBarController,取当前控制器
                UITabBarController *tabBarController = (UITabBarController *)controller;
                controller = tabBarController.selectedViewController;
            } else {
                if (controller.childViewControllers.count > 0) {
                    //如果是普通控制器,找childViewControllers最后一个
                    controller = [controller.childViewControllers lastObject];
                } else {
                    //没有present,没有childViewController,则表示当前控制器
                    return controller;
                }
            }
        }
    }
}

12.iOS去掉按钮的点击效果

button.adjustsImageWhenHighlighted = NO;

13.获取版本号

 //获得当前版本
NSString *currentVersion = [[[NSBundle mainBundle]infoDictionary]objectForKey:@"CFBundleShortVersionString"];

14.第一次启动

//第一次启动显示引导 if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunch"])
    {
       [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstLaunch"];

        NSLog(@"第一次启动");
    }
    else
    {
        NSLog(@"已经不是第一次启动了");
    }

15.代码执行一次

static dispatch_once_t disOnce;  
dispatch_once(&disOnce, ^ {  
//这里写只操作一次的代码  
});

16.存储图片到沙盒

NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
//  正确路径
NSString *filePath = [docPath stringByAppendingPathComponent:@"userData.data"];
//  错误路径
NSString *errorFilePath = [docPath stringByAppendingString:@"userData.data"];
NSData *imgData = UIImagePNGRepresentation(image);
[imgData writeToFile:filePath atomically:YES];

17.从沙盒读取照片

NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *filePath = [docPath stringByAppendingPathComponent:@"userData.data"];
NSData *imgData = [NSData dataWithContentsOfFile:filePath];
UIImage *image = [UIImage imageWithData:imgData];

18.字符串的截取(适用于所含字符串都不一样)

-(NSString *)returnToCutString:(NSString *)cutString begin:(NSString *)beginStirng end:(NSString *)endString{
    NSRange startRange = [cutString rangeOfString:beginStirng];
    NSRange endRange = [cutString rangeOfString:endString];
    NSRange range = NSMakeRange(startRange.location + startRange.length, endRange.location - startRange.location - startRange.length);
    NSString *result = [cutString substringWithRange:range];
    return result;
}

19.启动页一直停留直到做完了所有操作才消失

//在RootViewController中的ViewDidLoad中使用
    //1. 创建dispatch_semaphore
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    
    //2. 你的请求操作
    [HttpRequest  requestDataSuccess:^(NSDictionary *responseObj) {
        //4. 在你请求结束后调用diapatch_signal
        dispatch_semaphore_signal(semaphore);
    } failure:^(NSError *error) {
    }];
    
    //3. 然后调用diapatch_wait
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    
    //5. 显示界面
    UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(80, 100, 300, 50)];
    label.text=@"helloworld";
    label.textColor=[UIColor blueColor];
    [self.view addSubview:label];

你可能感兴趣的:(iOS 日常记录)