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];

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

推薦閱讀更多精彩內容

  • 1、通過CocoaPods安裝項目名稱項目信息 AFNetworking網絡請求組件 FMDB本地數據庫組件 SD...
    陽明AGI閱讀 16,003評論 3 119
  • 文|青三盜 近日。 不巧,一女孩遭遇其職場不幸,莫名其妙被算計,被迫離職。 緣起C部門一員工離職留一空缺,禍起未經...
    青三盜閱讀 293評論 0 1
  • 從北京周口店猿人到半坡母系氏族遺子 從古老的的榆樹人到勇敢的闖關東先祖 伐墾漁獵 種稻收麥 世世代代承接您的恩澤 ...
    王玉仙閱讀 354評論 1 1
  • 20180803,星期五,晴 四天前姨父說要去旅行,帶上一大家子人。他是一個愛熱鬧的人,說人多才有勁。于是也叫上了...
    妍妍520閱讀 222評論 0 0