1薯嗤、設置導航條的顏色及title顏色
在navgationController里設置
//設置NavigationBar背景顏色
[[UINavigationBar appearance] setBarTintColor:[UIColor blueColor]];
//@{}代表Dictionary
[[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
在viewController里設置
//set NavigationBar 背景顏色&title 顏色
[self.navigationController.navigationBar setBarTintColor:IFBackgroundColor];
[self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],UITextAttributeTextColor,nil]];
2.設置UIButton在選中狀態(tài)的背景顏色
3.從字符串中取出數(shù)字
/** ---------------------------------------------------------------------------*/
第一種:
字符串: urlString
NSScanner *scanner = [NSScanner scannerWithString:urlString];
[scanner scanUpToCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet] intoString:nil];
int number;
[scanner scanInt:&number];
NSString *num=[NSString stringWithFormat:@"%d",number];
/** ---------------------------------------------------------------------------*/
第二種:
字符串: urlString
NSCharacterSet* nonDigits =[[NSCharacterSet decimalDigitCharacterSet] invertedSet];
int remainSecond =[[urlString stringByTrimmingCharactersInSet:nonDigits] intValue];
NSLog(@" num %d ",remainSecond);
4.顏色轉(zhuǎn)換為背景圖片
//顏色轉(zhuǎn)換為背景圖片
-(UIImage *)imageWithColor:(UIColor *)color {
CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
5.CoreText實現(xiàn)圖文混排之文字環(huán)繞及點擊算法
http://blog.csdn.net/qq_30513483/article/details/53883865
6.UILabel顯示HTML文本
NSString * htmlString = @"<html><body> Some html string \n <font size=\"13\"color=\"red\">This is some text!</font> </body></html>";
NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
UILabel * myLabel = [[UILabel alloc] initWithFrame:self.view.bounds];
myLabel.attributedText = attrStr;
[self.view addSubview:myLabel];
7.正則匹配html 代碼中的圖片
- (NSArray *)filterImage:(NSString *)html
{
NSMutableArray *resultArray = [NSMutableArray array];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"<(img|IMG)(.*?)(/>|></img>|>)" options:NSRegularExpressionAllowCommentsAndWhitespace error:nil];
NSArray *result = [regex matchesInString:html options:NSMatchingReportCompletion range:NSMakeRange(0, html.length)];
for (NSTextCheckingResult *item in result) {
NSString *imgHtml = [html substringWithRange:[item rangeAtIndex:0]];
NSArray *tmpArray = nil;
if ([imgHtml rangeOfString:@"src=\""].location != NSNotFound) {
tmpArray = [imgHtml componentsSeparatedByString:@"src=\""];
} else if ([imgHtml rangeOfString:@"src="].location != NSNotFound) {
tmpArray = [imgHtml componentsSeparatedByString:@"src="];
}
if (tmpArray.count >= 2) {
NSString *src = tmpArray[1];
NSUInteger loc = [src rangeOfString:@"\""].location;
if (loc != NSNotFound) {
src = [src substringToIndex:loc];
[resultArray addObject:src];
}
}
}
return resultArray;
}
8.不運行xcode 查看打印日志的方法
方法一:手機連上電腦,打開Xcode纤泵,選擇菜單中的‘Window’ -> 'Devices',這里可以看到所以打印的日志(不只是你的app)
方法二:可以添加代碼骆姐,寫到沙盒中的文件去,在plist中設置可以共享捏题,然后運行玻褪,就可以用iTune找到相應文件。不過這個代碼量比較大公荧,而且只能用于調(diào)試归园。
9.AFNetWorking Post請求,請求參數(shù)放在Body處
10.時間段判斷
方法一:
/**
* 判斷當前時間是否處于某個時間段內(nèi)
*
* @param startTime 開始時間
* @param expireTime 結(jié)束時間
*/
- (BOOL)validateWithStartTime:(NSString *)startTime withExpireTime:(NSString *)expireTime {
NSDate *today = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
// 時間格式,此處遇到過坑,建議時間HH大寫,手機24小時進制和12小時進制都可以完美格式化
[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
NSDate *start = [dateFormat dateFromString:startTime];
NSDate *expire = [dateFormat dateFromString:expireTime];
NSLog(@"---===%@",dateFormat);
if ([today compare:start] == NSOrderedDescending && [today compare:expire] == NSOrderedAscending) {
return YES;
}
return NO;
}
方法二:
/**
if ([self isBetweenFromHour:9 toHour:15]) {
LOG(@"處于時間段內(nèi)");
}else {
LOG(@"處于時間段外");
}
* @brief 判斷當前時間是否在fromHour和toHour之間稚矿。如, fromHour=8捻浦,toHour=23時晤揣,即為判斷當前時間是否在8:00-23:00之間
*/
- (BOOL)isBetweenFromHour:(NSInteger)fromHour andMinute:(NSInteger)fromMinute toHour:(NSInteger)toHour andToMinute:(NSInteger)toMinute {
NSDate *dateFrom = [self getCustomDateWithHour:fromHour minute:fromMinute];
NSDate *dateTo = [self getCustomDateWithHour:toHour minute:toMinute];
NSDate *currentDate = [NSDate date];
// NSLog(@"dateFrom=%@---dateTo=%@---currentDate=%@",dateFrom,dateTo,currentDate);
if ([currentDate compare:dateFrom]==NSOrderedDescending && [currentDate compare:dateTo]==NSOrderedAscending) {
// 當前時間在9點和10點之間
return YES;
}
return NO;
}
/**
* @brief 生成當天的某個點(返回的是倫敦時間,可直接與當前時間[NSDate date]比較)
* @param hour 如hour為“8”朱灿,就是上午8:00(本地時間)
*/
- (NSDate *)getCustomDateWithHour:(NSInteger)hour minute:(NSInteger)minute {
//獲取當前時間
NSDate *currentDate = [NSDate date];
NSCalendar *currentCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *currentComps = [[NSDateComponents alloc] init];
NSInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
currentComps = [currentCalendar components:unitFlags fromDate:currentDate];
//設置當天的某個點
NSDateComponents *resultComps = [[NSDateComponents alloc] init];
[resultComps setYear:[currentComps year]];
[resultComps setMonth:[currentComps month]];
[resultComps setDay:[currentComps day]];
[resultComps setHour:hour];
[resultComps setMinute:minute];
NSCalendar *resultCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
return [resultCalendar dateFromComponents:resultComps];
}
11 cocoapods報錯
- Use the `$(inherited)` flag, or
- Remove the build settings from the target.
解決辦法:Go to your target Build Settings -> Other linker flags -> double click . Add $(inherited) to a new line.然后進入終端昧识,執(zhí)行pod update
網(wǎng)上還流行另外一種簡單粗暴的方法:點擊項目文件 project.xcodeproj,右鍵
顯示包內(nèi)容
盗扒,用文本編輯器打開project.pbxproj
跪楞,刪除OTHER_LDFLAGS
的地方,保存侣灶,回到 Xcode甸祭,編譯通過。
12 UITextfield小數(shù)點后只顯示兩位有效數(shù)字
方法一:
@property (nonatomic, assign) BOOL isHaveDian;
@property (nonatomic, assign) BOOL isFirstZero;
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (textField == self.textField) {
if ([textField.text rangeOfString:@"."].location==NSNotFound) {
_isHaveDian = NO;
}
if ([textField.text rangeOfString:@"0"].location==NSNotFound) {
_isFirstZero = NO;
}
if ([string length]>0)
{
unichar single=[string characterAtIndex:0];//當前輸入的字符
if ((single >='0' && single<='9') || single=='.')//數(shù)據(jù)格式正確
{
if([textField.text length]==0){
if(single == '.'){
//首字母不能為小數(shù)點
return NO;
}
if (single == '0') {
_isFirstZero = YES;
return YES;
}
}
if (single=='.'){
if(!_isHaveDian)//text中還沒有小數(shù)點
{
_isHaveDian=YES;
return YES;
}else{
return NO;
}
}else if(single=='0'){
if ((_isFirstZero&&_isHaveDian)||(!_isFirstZero&&_isHaveDian)) {
//首位有0有.(0.01)或首位沒0有.(10200.00)可輸入兩位數(shù)的0
if([textField.text isEqualToString:@"0.0"]){
return NO;
}
NSRange ran=[textField.text rangeOfString:@"."];
int tt=(int)(range.location-ran.location);
if (tt <= 2){
return YES;
}else{
return NO;
}
}else if (_isFirstZero&&!_isHaveDian){
//首位有0沒.不能再輸入0
return NO;
}else{
return YES;
}
}else{
if (_isHaveDian){
//存在小數(shù)點褥影,保留兩位小數(shù)
NSRange ran=[textField.text rangeOfString:@"."];
int tt= (int)(range.location-ran.location);
if (tt <= 2){
return YES;
}else{
return NO;
}
}else if(_isFirstZero&&!_isHaveDian){
//首位有0沒點
return NO;
}else{
return YES;
}
}
}else{
//輸入的數(shù)據(jù)格式不正確
return NO;
}
}else{
return YES;
}
}
return YES;
}
方法二:
// 小數(shù)點后只顯示兩位有效數(shù)字
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
//刪除處理
if ([string isEqualToString:@""]) {
return YES;
}
//首位不能為.號
if (range.location == 0 && [string isEqualToString:@"."]) {
return NO;
}
return [self isRightInPutOfString:textField.text withInputString:string range:range];
}
- (BOOL)isRightInPutOfString:(NSString *) string withInputString:(NSString *) inputString range:(NSRange) range{
//判斷只輸出數(shù)字和.號
NSString *passWordRegex = @"[0-9\\.]";
NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passWordRegex];
if (![passWordPredicate evaluateWithObject:inputString]) {
return NO;
}
//邏輯處理
if ([string containsString:@"."]) {
if ([inputString isEqualToString:@"."]) {
return NO;
}
NSRange subRange = [string rangeOfString:@"."];
if (range.location - subRange.location > 2) {
return NO;
}
}
return YES;
}
13 AutoLayout下多行UILabel無法顯示多行文本的問題
設置UILabel的preferredMaxLayoutWidth屬性
14 數(shù)組的排序(升序池户、降序及亂序)
#pragma mark -- 數(shù)組排序方法(升序)
- (void)arraySortASC {
//定義一個數(shù)字數(shù)組
// NSArray *array = @[@"B",@"E",@"A",@"D",@"C"];
//對數(shù)組進行排序
NSArray *result = [array sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
NSLog(@"%@~%@",obj1,obj2); //3~4 2~1 3~1 3~2
return [obj1 compare:obj2]; //升序
}];
NSLog(@"result=%@",result);
}
#pragma mark -- 數(shù)組排序方法(降序)
- (void)arraySortDESC{
//定義一個數(shù)字數(shù)組
NSArray *array = @[@(3),@(4),@(2),@(1)];
//對數(shù)組進行排序
NSArray *result = [array sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
NSLog(@"%@~%@",obj1,obj2); //3~4 2~1 3~1 3~2
return [obj2 compare:obj1]; //降序
}];
NSLog(@"result=%@",result);
}
#pragma mark -- 數(shù)組排序方法(亂序)
- (void)arraySortBreak{
//定義一個數(shù)字數(shù)組
NSArray *array = @[@(3),@(4),@(2),@(1),@(5),@(6),@(0)];
//對數(shù)組進行排序
NSArray *result = [array sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
NSLog(@"%@~%@",obj1,obj2);
//亂序
if (arc4random_uniform(2) == 0) {
return [obj2 compare:obj1]; //降序
}
else{
return [obj1 compare:obj2]; //升序
}
}];
NSLog(@"result=%@",result);
}
15 iOS APP上傳iTunes Store 時,報錯 An error occurred uploading to the iTunes Store凡怎!
1.Open the terminal and run these commands:
cd ~
mv .itmstransporter/ .old_itmstransporter/
2.把發(fā)布證書刪除了校焦,重新創(chuàng)建
3.解決打包上傳一直停留在authenticating with the itunes store問題
1. cd ~
2. mv .itmstransporter/ .old_itmstransporter/
3. "/Applications/Xcode.app/Contents/Applications/Application Loader.app/Contents/itms/bin/iTMSTransporter"
注意:一定要等第三條命令執(zhí)行完畢才可以哦!
16.webview高度
// 網(wǎng)頁開始加載完成
- (void)webViewDidFinishLoad:(UIWebView *)webView {
newsDetails_H = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];
}
17.強制刪除iTunes
18,版本更新提示
http://www.reibang.com/p/032b5eb67002
1)后臺版本判斷(推薦)
2)ios端版本判斷(不建議使用)
#pragma mark - checkV
-(void)VersonUpdate{
//定義的app的地址
NSString *urld = [NSString stringWithFormat:@"http://itunes.apple.com/lookup?id=%@",@"appID"];
//網(wǎng)絡請求app的信息统倒,主要是取得我說需要的Version
NSURL *url = [NSURL URLWithString:urld];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:10];
[request setHTTPMethod:@"POST"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSMutableDictionary *receiveStatusDic=[[NSMutableDictionary alloc]init];
if (data) {
//data是有關于App所有的信息
NSDictionary *receiveDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
if ([[receiveDic valueForKey:@"resultCount"] intValue]>0) {
[receiveStatusDic setValue:@"1" forKey:@"status"];
[receiveStatusDic setValue:[[[receiveDic valueForKey:@"results"] objectAtIndex:0] valueForKey:@"version"] forKey:@"version"];
//請求的有數(shù)據(jù)寨典,進行版本比較
[self performSelectorOnMainThread:@selector(receiveData:) withObject:receiveStatusDic waitUntilDone:NO];
}else{
[receiveStatusDic setValue:@"-1" forKey:@"status"];
}
}else{
[receiveStatusDic setValue:@"-1" forKey:@"status"];
}
}];
[task resume];
}
-(void)receiveData:(id)sender
{
//獲取APP自身版本號
NSString *localVersion = [[[NSBundle mainBundle]infoDictionary]objectForKey:@"CFBundleShortVersionString"];
NSArray *localArray = [localVersion componentsSeparatedByString:@"."];
NSArray *versionArray = [sender[@"version"] componentsSeparatedByString:@"."];
if ((versionArray.count == 3) && (localArray.count == versionArray.count)) {
if ([localArray[0] intValue] < [versionArray[0] intValue]) {
[self updateVersion];
}else if ([localArray[0] intValue] == [versionArray[0] intValue]){
if ([localArray[1] intValue] < [versionArray[1] intValue]) {
[self updateVersion];
}else if ([localArray[1] intValue] == [versionArray[1] intValue]){
if ([localArray[2] intValue] < [versionArray[2] intValue]) {
[self updateVersion];
}
}
}
}
}
-(void)updateVersion{
NSString *msg = [NSString stringWithFormat:@"升級到最新版本"];
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"升級提示" message:msg preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"現(xiàn)在升級"style:UIAlertActionStyleDestructive handler:^(UIAlertAction*action) {
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"你的app在商店的下載地址"]];
[[UIApplication sharedApplication]openURL:url];
}];
[alertController addAction:otherAction];
[self.window.rootViewController presentViewController:alertController animated:YES completion:nil];
}
19.程序生命周期
AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
#pragma mark -- NSLog(@"\n ===> 程序開始 !");
self.window = [[UIWindow alloc]initWithFrame:CGRectMake(0, 0, SCREENW, SCREENH)];
self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:[[ViewController alloc]init]];
[self.window makeKeyAndVisible];
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application {
#pragma mark -->NSLog(@"\n ===> 程序掛起 !");
#pragma mark -->比如:當有電話進來或者鎖屏,這時你的應用程會掛起房匆,在這時耸成,UIApplicationDelegate委托會收到通知报亩,調(diào)用 applicationWillResignActive 方法,你可以重寫這個方法墓猎,做掛起前的工作捆昏,比如關閉網(wǎng)絡,保存數(shù)據(jù)毙沾。
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
#pragma mark --> NSLog(@"\n ===> 程序進入后臺 !");
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
#pragma mark --> NSLog(@"\n ===> 程序進入前臺 !");
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
#pragma mark --> NSLog(@"\n ===> 程序重新激活 !");
#pragma mark -->應用程序在啟動時骗卜,在調(diào)用了 applicationDidFinishLaunching 方法之后也會調(diào)用 applicationDidBecomeActive 方法,所以你要確保你的代碼能夠分清復原與啟動左胞,避免出現(xiàn)邏輯上的bug寇仓。(大白話就是說:只要啟動app就會走此方法)。
}
- (void)applicationWillTerminate:(UIApplication *)application {
#pragma mark --> 當用戶按下按鈕烤宙,或者關機遍烦,程序都會被終止。當一個程序?qū)⒁=K止時會調(diào)用 applicationWillTerminate 方法躺枕。但是如果長主按鈕強制退出服猪,則不會調(diào)用該方法。這個方法該執(zhí)行剩下的清理工作拐云,比如所有的連接都能正常關閉罢猪,并在程序退出前執(zhí)行任何其他的必要的工作.
}
20.解決ios11的下移問題
//解決ios11的下移問題
if ([_YDHomeTableView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
if (@available(iOS 11.0, *)) {
_YDHomeTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
} else {
}
}
21.獲取圖片大小
//獲取本地圖片的size
CGSize size = [UIImage imageNamed:@"圖片"].size;
// 根據(jù)圖片url獲取圖片尺寸
+(CGSize)getImageSizeWithURL:(id)imageURL
{
NSURL* URL = nil;
if([imageURL isKindOfClass:[NSURL class]]){
URL = imageURL;
}
if([imageURL isKindOfClass:[NSString class]]){
URL = [NSURL URLWithString:imageURL];
}
if(URL == nil)
return CGSizeZero; // url不正確返回CGSizeZero
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:URL];
NSString* pathExtendsion = [URL.pathExtension lowercaseString];
CGSize size = CGSizeZero;
if([pathExtendsion isEqualToString:@"png"]){
size = [self getPNGImageSizeWithRequest:request];
}
else if([pathExtendsion isEqual:@"gif"])
{
size = [self getGIFImageSizeWithRequest:request];
}
else{
size = [self getJPGImageSizeWithRequest:request];
}
if(CGSizeEqualToSize(CGSizeZero, size)) // 如果獲取文件頭信息失敗,發(fā)送異步請求請求原圖
{
NSData* data = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:URL] returningResponse:nil error:nil];
UIImage* image = [UIImage imageWithData:data];
if(image)
{
size = image.size;
}
}
return size;
}
// 獲取PNG圖片的大小
+(CGSize)getPNGImageSizeWithRequest:(NSMutableURLRequest*)request
{
[request setValue:@"bytes=16-23" forHTTPHeaderField:@"Range"];
NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
if(data.length == 8)
{
int w1 = 0, w2 = 0, w3 = 0, w4 = 0;
[data getBytes:&w1 range:NSMakeRange(0, 1)];
[data getBytes:&w2 range:NSMakeRange(1, 1)];
[data getBytes:&w3 range:NSMakeRange(2, 1)];
[data getBytes:&w4 range:NSMakeRange(3, 1)];
int w = (w1 << 24) + (w2 << 16) + (w3 << 8) + w4;
int h1 = 0, h2 = 0, h3 = 0, h4 = 0;
[data getBytes:&h1 range:NSMakeRange(4, 1)];
[data getBytes:&h2 range:NSMakeRange(5, 1)];
[data getBytes:&h3 range:NSMakeRange(6, 1)];
[data getBytes:&h4 range:NSMakeRange(7, 1)];
int h = (h1 << 24) + (h2 << 16) + (h3 << 8) + h4;
return CGSizeMake(w, h);
}
return CGSizeZero;
}
// 獲取gif圖片的大小
+(CGSize)getGIFImageSizeWithRequest:(NSMutableURLRequest*)request
{
[request setValue:@"bytes=6-9" forHTTPHeaderField:@"Range"];
NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
if(data.length == 4)
{
short w1 = 0, w2 = 0;
[data getBytes:&w1 range:NSMakeRange(0, 1)];
[data getBytes:&w2 range:NSMakeRange(1, 1)];
short w = w1 + (w2 << 8);
short h1 = 0, h2 = 0;
[data getBytes:&h1 range:NSMakeRange(2, 1)];
[data getBytes:&h2 range:NSMakeRange(3, 1)];
short h = h1 + (h2 << 8);
return CGSizeMake(w, h);
}
return CGSizeZero;
}
// 獲取jpg圖片的大小
+(CGSize)getJPGImageSizeWithRequest:(NSMutableURLRequest*)request
{
[request setValue:@"bytes=0-209" forHTTPHeaderField:@"Range"];
NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
if ([data length] <= 0x58) {
return CGSizeZero;
}
if ([data length] < 210) {// 肯定只有一個DQT字段
short w1 = 0, w2 = 0;
[data getBytes:&w1 range:NSMakeRange(0x60, 0x1)];
[data getBytes:&w2 range:NSMakeRange(0x61, 0x1)];
short w = (w1 << 8) + w2;
short h1 = 0, h2 = 0;
[data getBytes:&h1 range:NSMakeRange(0x5e, 0x1)];
[data getBytes:&h2 range:NSMakeRange(0x5f, 0x1)];
short h = (h1 << 8) + h2;
return CGSizeMake(w, h);
} else {
short word = 0x0;
[data getBytes:&word range:NSMakeRange(0x15, 0x1)];
if (word == 0xdb) {
[data getBytes:&word range:NSMakeRange(0x5a, 0x1)];
if (word == 0xdb) {// 兩個DQT字段
short w1 = 0, w2 = 0;
[data getBytes:&w1 range:NSMakeRange(0xa5, 0x1)];
[data getBytes:&w2 range:NSMakeRange(0xa6, 0x1)];
short w = (w1 << 8) + w2;
short h1 = 0, h2 = 0;
[data getBytes:&h1 range:NSMakeRange(0xa3, 0x1)];
[data getBytes:&h2 range:NSMakeRange(0xa4, 0x1)];
short h = (h1 << 8) + h2;
return CGSizeMake(w, h);
} else {// 一個DQT字段
short w1 = 0, w2 = 0;
[data getBytes:&w1 range:NSMakeRange(0x60, 0x1)];
[data getBytes:&w2 range:NSMakeRange(0x61, 0x1)];
short w = (w1 << 8) + w2;
short h1 = 0, h2 = 0;
[data getBytes:&h1 range:NSMakeRange(0x5e, 0x1)];
[data getBytes:&h2 range:NSMakeRange(0x5f, 0x1)];
short h = (h1 << 8) + h2;
return CGSizeMake(w, h);
}
} else {
return CGSizeZero;
}
}
}
22. iOS獲取本機的UDID
什么是UDID?
UDID,是iOS設備的一個唯一識別碼叉瘩,每臺iOS設備都有一個獨一無二的編碼膳帕,這個編碼,我們稱之為識別碼薇缅,也叫做UDID( Unique Device Identifier)危彩。
1.使用蒲公英一步快速獲取 iOS 設備的 UDID
使用 iPhone 或 iPad 上的 Safari 瀏覽器打開鏈接:https://www.pgyer.com/udid,即可快速獲取 UDID(如果系統(tǒng)提示輸入密碼泳桦,請輸入鎖屏密碼汤徽。)
2.iOS獲取本機的UDID命令行
在終端輸入命令行
instruments-s|awk'{print $NR}'|sed-n3p|awk'{print substr($0,2,length($0)-2)}'|xargsrvictl-s
然后只要連上手機,就可以直接獲取到 UDID 了
UDID :是用來標示設備的唯一性灸撰。
UUID :是用來標示同一個設備上不同應用之間的唯一性泻骤。
23. iOS獲取手機殼顏色
- (void)getPhoneColor {
NSString *deviceColor;
NSString *deviceEnclosureColor;//手機殼顏色
UIDevice *device = [UIDevice currentDevice];
SEL selector = NSSelectorFromString(@"deviceInfoForKey:");
if (![device respondsToSelector:selector]) {
selector = NSSelectorFromString(@"_deviceInfoForKey:");
}
if ([device respondsToSelector:selector]) {
IMP imp = [device methodForSelector:selector];
NSString *(*func)(id, SEL, NSString *) = (void *)imp;
deviceColor = func(device, selector, @"DeviceColor");
deviceEnclosureColor = func(device, selector, @"DeviceEnclosureColor");
NSLog(@"color=%@,手機殼顏色=%@",deviceColor,deviceEnclosureColor);
}
UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(100, 150, 60, 100)];
[self.view addSubview:view1];
view1.backgroundColor=[self colorWithHexString:deviceEnclosureColor];
}
- (UIColor *) colorWithHexString: (NSString *)color {
NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
// String should be 6 or 8 characters
if ([cString length] < 6) {
return [UIColor clearColor];
}
// 判斷前綴
if ([cString hasPrefix:@"0X"])
cString = [cString substringFromIndex:2];
if ([cString hasPrefix:@"#"])
cString = [cString substringFromIndex:1];
if ([cString length] != 6)
return [UIColor clearColor];
// 從六位數(shù)值中找到RGB對應的位數(shù)并轉(zhuǎn)換
NSRange range;
range.location = 0;
range.length = 2;
//R梧奢、G狱掂、B
NSString *rString = [cString substringWithRange:range];
range.location = 2;
NSString *gString = [cString substringWithRange:range];
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:1.0f];
}
24.WKWebView獲取內(nèi)容高度建議使用方法
[webView evaluateJavaScript:@"document.body.offsetHeight;" completionHandler:^(id _Nullable any, NSError * _Nullable error) {
//webView內(nèi)容高度
NSString *heightStr = [NSString stringWithFormat:@"%@",any];
}];
25.獲取圖片NSData的格式
- (NSString *)contentTypeForImageData:(NSData *)data
{
uint8_t c;
[data getBytes:&c length:1];
switch (c)
{
case 0xFF:
return @"jpeg";
case 0x89:
return @"png";
case 0x47:
return @"gif";
case 0x49:
case 0x4D:
return @"tiff";
case 0x52:
if ([data length] < 12) {
return nil;
}
NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding];
if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) {
return @"webp";
}
return nil;
}
return nil;
}
26.修改導航欄標題顏色
[self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor redColor],
NSFontAttributeName : [UIFont systemFontOfSize:18]}]
27.判斷iPhoneX及以上
[UIApplication sharedApplication].statusBarFrame.size.height > 20
27.push的時候tabbar錯位的了問題
[[UITabBar appearance] setTranslucent:NO];
28.解決導航欄上下兩個顏色值是一樣的顯示了不一樣的顏色,去除中間的分隔線
導航條設置了透明
[self.navigationController.navigationBar setShadowImage:[UIImage imageWithColor:[UIColor clearColor]]];
+ (UIImage *)imageWithColor:(UIColor *)color {
return [self imageWithColor:color size:CGSizeMake(1, 1)];
}
+ (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size {
if (!color || size.width <= 0 || size.height <= 0) return nil;
CGRect rect = CGRectMake(0.0f, 0.0f, size.width, size.height);
UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, color.CGColor);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
29.解決Xcode控制臺打印[] nw_host_stats_add_src received error for SRC_ADDED: [22] Invalid argument, dumping backtrace:
1.選擇 Product –>Scheme–>Edit Scheme
2.選擇 Arguments
3.在Environment Variables添加一個環(huán)境變量 “OS_ACTIVITY_MODE” 設置值為 “disable”
4.clean和build一下
5.重新運行
29.tableviewheader 高度自適應
oc版
_headView = [[IFYStoreHead alloc] init];
CGFloat height = [_headView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
CGRect frame = _headView.bounds;
frame.size.height = height;
_headView.frame = frame;
self.tableView.tableHeaderView = _headView;
swift版
func headFramechange() {
tableview.beginUpdates()
sizeHeaderToFit()
tableview.endUpdates()
}
//自適應tableviewHead
func sizeHeaderToFit() {
headerView.setNeedsLayout()
headerView.layoutIfNeeded()
let height = headerView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
var frame = headerView.frame
frame.size.height = height
headerView.frame = frame
tableview.tableHeaderView = headerView
}
30.查看字體庫所有字體
- (void)getAllFontName {
NSArray *familyNames = [[NSArray alloc] initWithArray:[UIFont familyNames]];
for(int i=0;i<[familyNames count];++i)
{
NSLog(@">>>%@",[UIFont fontNamesForFamilyName:[familyNames objectAtIndex:i]]);
}
}
31.windows展示文字
//windows展示文字
#define WindowsHUDShowTextWithDelayTime(text) UIWindow * view = [[[UIApplication sharedApplication] delegate] window];\
NSArray *windows = [UIApplication sharedApplication].windows;\
for (id windowView in windows) {\
NSString *viewName = NSStringFromClass([windowView class]);\
if ([@"UIRemoteKeyboardWindow" isEqualToString:viewName]) {\
view = windowView;\
break;\
}\
}\
CSToastStyle * style = [CSToastManager sharedStyle];\
style.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.8];\
style.titleColor = [UIColor whiteColor];\
style.messageColor = [UIColor whiteColor];\
[view makeToast:text duration:2 position:CSToastPositionCenter]
32. App在appstore下載地址
App的下載地址格式是固定的亲轨,如下趋惨,鏈接中的989673964是AppID,你如果知道某個App的AppID惦蚊,直接替換就是對應的下載地址
https://itunes.apple.com/cn/app/id989673964?mt=8
(WWDC2019后Apple廢棄了itunes器虾,域名也發(fā)生了變化)
https://apps.apple.com/cn/app/id989673964
33.
xcode 更新11后讯嫂,+[_LSDefaults sharedInstance]: unrecognized selector sent to class 0x1ef416aa0
添加下面的.h.m
// 解決xcode11無故閃退原因 +[_LSDefaults sharedInstance]: unrecognized selector sent to class 0x1cbcd6aa0
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface NSObject (BTExtend)
@end
NS_ASSUME_NONNULL_END
#import "NSObject+BTExtend.h"
@implementation NSObject (BTExtend)
+ (void)load{
SEL originalSelector = @selector(doesNotRecognizeSelector:);
SEL swizzledSelector = @selector(sw_doesNotRecognizeSelector:);
Method originalMethod = class_getClassMethod(self, originalSelector);
Method swizzledMethod = class_getClassMethod(self, swizzledSelector);
if(class_addMethod(self, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))){
class_replaceMethod(self, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
}else{
method_exchangeImplementations(originalMethod, swizzledMethod);
}
}
+ (void)sw_doesNotRecognizeSelector:(SEL)aSelector{
//處理 _LSDefaults 崩潰問題
if([[self description] isEqualToString:@"_LSDefaults"] && (aSelector == @selector(sharedInstance))){
//冷處理...
return;
}
[self sw_doesNotRecognizeSelector:aSelector];
}
@end