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