iOS小技巧總結###
總結日常代碼生活中的小技巧,隨時可用
阿拉伯數(shù)字轉中文格式
阿拉伯數(shù)字轉中文格式
UITextField每四位加一個空格,實現(xiàn)代理
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
// 四位加一個空格
if ([string isEqualToString:@""])
{
// 刪除字符
if ((textField.text.length - 2) % 5 == 0)
{
textField.text = [textField.text substringToIndex:textField.text.length - 1];
}
return YES;
}
else
{
if (textField.text.length % 5 == 0)
{
textField.text = [NSString stringWithFormat:@"%@ ", textField.text];
}
}
return YES;
}
禁止鎖屏
默認情況下嘲碱,當設備一段時間沒有觸控動作時,iOS會鎖住屏幕木蹬。但有一些應用是不需要鎖屏的蝇恶,比如視頻播放器。
[UIApplication sharedApplication].idleTimerDisabled = YES;
或
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];
iOS 獲取漢字的拼音
+ (NSString *)transform:(NSString *)chinese
{
//將NSString裝換成NSMutableString
NSMutableString *pinyin = [chinese mutableCopy];
//將漢字轉換為拼音(帶音標)
CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);
NSLog(@"%@", pinyin);
//去掉拼音的音標
CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO);
NSLog(@"%@", pinyin);
//返回最近結果
return pinyin;
}
手動更改iOS狀態(tài)欄的顏色
- (void)setStatusBarBackgroundColor:(UIColor *)color
{
UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
if ([statusBar respondsToSelector:@selector(setBackgroundColor:)])
{
statusBar.backgroundColor = color;
}
}
NSArray 快速求總和 最大值 最小值 和 平均值
NSArray *array = [NSArray arrayWithObjects:@"2.0", @"2.3", @"3.0", @"4.0", @"10", nil];
CGFloat sum = [[array valueForKeyPath:@"@sum.floatValue"] floatValue];
CGFloat avg = [[array valueForKeyPath:@"@avg.floatValue"] floatValue];
CGFloat max =[[array valueForKeyPath:@"@max.floatValue"] floatValue];
CGFloat min =[[array valueForKeyPath:@"@min.floatValue"] floatValue];
NSLog(@"%f\n%f\n%f\n%f",sum,avg,max,min);
修改UITextField中Placeholder的文字顏色
[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
或
textField.tintColor = [UIColor redColor];
關于NSDateFormatter的格式
G: 公元時代苗胀,例如AD公元
yy: 年的后2位
yyyy: 完整年
MM: 月狡刘,顯示為1-12
MMM: 月享潜,顯示為英文月份簡寫,如 Jan
MMMM: 月,顯示為英文月份全稱颓帝,如 Janualy
dd: 日米碰,2位數(shù)表示,如02
d: 日购城,1-2位顯示吕座,如 2
EEE: 簡寫星期幾,如Sun
EEEE: 全寫星期幾瘪板,如Sunday
aa: 上下午吴趴,AM/PM
H: 時,24小時制侮攀,0-23
K:時锣枝,12小時制,0-11
m: 分兰英,1-2位
mm: 分撇叁,2位
s: 秒,1-2位
ss: 秒畦贸,2位
S: 毫秒
UIImage 占用內存大小
UIImage *image = [UIImage imageNamed:@"aa"];
NSUInteger size = CGImageGetHeight(image.CGImage) * CGImageGetBytesPerRow(image.CGImage);
圖片上繪制文字 寫一個UIImage的category
- (UIImage *)imageWithTitle:(NSString *)title fontSize:(CGFloat)fontSize
{
//畫布大小
CGSize size=CGSizeMake(self.size.width,self.size.height);
//創(chuàng)建一個基于位圖的上下文
UIGraphicsBeginImageContextWithOptions(size,NO,0.0);//opaque:NO scale:0.0
[self drawAtPoint:CGPointMake(0.0,0.0)];
//文字居中顯示在畫布上
NSMutableParagraphStyle* paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
paragraphStyle.alignment=NSTextAlignmentCenter;//文字居中
//計算文字所占的size,文字居中顯示在畫布上
CGSize sizeText=[title boundingRectWithSize:self.size options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]}context:nil].size;
CGFloat width = self.size.width;
CGFloat height = self.size.height;
CGRect rect = CGRectMake((width-sizeText.width)/2, (height-sizeText.height)/2, sizeText.width, sizeText.height);
//繪制文字
[title drawInRect:rect withAttributes:@{ NSFontAttributeName:[UIFont systemFontOfSize:fontSize],NSForegroundColorAttributeName:[ UIColor whiteColor],NSParagraphStyleAttributeName:paragraphStyle}];
//返回繪制的新圖形
UIImage *newImage= UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
計算文件大小
//文件大小
- (long long)fileSizeAtPath:(NSString *)path
{
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:path])
{
long long size = [fileManager attributesOfItemAtPath:path error:nil].fileSize;
return size;
}
return 0;
}
//文件夾大小
- (long long)folderSizeAtPath:(NSString *)path
{
NSFileManager *fileManager = [NSFileManager defaultManager];
long long folderSize = 0;
if ([fileManager fileExistsAtPath:path])
{
NSArray *childerFiles = [fileManager subpathsAtPath:path];
for (NSString *fileName in childerFiles)
{
NSString *fileAbsolutePath = [path stringByAppendingPathComponent:fileName];
if ([fileManager fileExistsAtPath:fileAbsolutePath])
{
long long size = [fileManager attributesOfItemAtPath:fileAbsolutePath error:nil].fileSize;
folderSize += size;
}
}
}
return folderSize;
}
給UIView設置圖片
UIImage *image = [UIImage imageNamed:@"image"];
self.MYView.layer.contents = (__bridge id _Nullable)(image.CGImage);
self.MYView.layer.contentsRect = CGRectMake(0, 0, 0.5, 0.5);
防止scrollView手勢覆蓋側滑手勢
[scrollView.panGestureRecognizerrequireGestureRecognizerToFail:self.navigationController.interactivePopGestureRecognizer];
獲取私有屬性和成員變量 #import <objc/runtime.h>
//獲取私有屬性 比如設置UIDatePicker的字體顏色
- (void)setTextColor
{
//獲取所有的屬性陨闹,去查看有沒有對應的屬性
unsigned int count = 0;
objc_property_t *propertys = class_copyPropertyList([UIDatePicker class], &count);
for(int i = 0;i < count;i ++)
{
//獲得每一個屬性
objc_property_t property = propertys[i];
//獲得屬性對應的nsstring
NSString *propertyName = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
//輸出打印看對應的屬性
NSLog(@"propertyname = %@",propertyName);
if ([propertyName isEqualToString:@"textColor"])
{
[datePicker setValue:[UIColor whiteColor] forKey:propertyName];
}
}
}
//獲得成員變量 比如修改UIAlertAction的按鈕字體顏色
unsigned int count = 0;
Ivar *ivars = class_copyIvarList([UIAlertAction class], &count);
for(int i =0;i < count;i ++)
{
Ivar ivar = ivars[i];
NSString *ivarName = [NSString stringWithCString:ivar_getName(ivar) encoding:NSUTF8StringEncoding];
NSLog(@"uialertion.ivarName = %@",ivarName);
if ([ivarName isEqualToString:@"_titleTextColor"])
{
[alertOk setValue:[UIColor blueColor] forKey:@"titleTextColor"];
[alertCancel setValue:[UIColor purpleColor] forKey:@"titleTextColor"];
}
}
獲取手機安裝的應用
Class c =NSClassFromString(@"LSApplicationWorkspace");
id s = [(id)c performSelector:NSSelectorFromString(@"defaultWorkspace")];
NSArray *array = [s performSelector:NSSelectorFromString(@"allInstalledApplications")];
for (id item in array)
{
NSLog(@"%@",[item performSelector:NSSelectorFromString(@"applicationIdentifier")]);
//NSLog(@"%@",[item performSelector:NSSelectorFromString(@"bundleIdentifier")]);
NSLog(@"%@",[item performSelector:NSSelectorFromString(@"bundleVersion")]);
NSLog(@"%@",[item performSelector:NSSelectorFromString(@"shortVersionString")]);
}
判斷兩個日期是否在同一周 寫在NSDate的category里面
- (BOOL)isSameDateWithDate:(NSDate *)date
{
//日期間隔大于七天之間返回NO
if (fabs([self timeIntervalSinceDate:date]) >= 7 * 24 *3600)
{
return NO;
}
NSCalendar *calender = [NSCalendar currentCalendar];
calender.firstWeekday = 2;//設置每周第一天從周一開始
//計算兩個日期分別為這年第幾周
NSUInteger countSelf = [calender ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitYear forDate:self];
NSUInteger countDate = [calender ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitYear forDate:date];
//相等就在同一周跌造,不相等就不在同一周
return countSelf == countDate;
}
應用內打開系統(tǒng)設置界面
//iOS8之后
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
//如果App沒有添加權限卷胯,顯示的是設定界面夺欲。如果App有添加權限(例如通知)府阀,顯示的是App的設定界面留潦。
獲取WebView所有的圖片地址
在網頁加載完成時燥撞,通過js獲取圖片和添加點擊的識別方式
//UIWebView
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
//這里是js酝惧,主要目的實現(xiàn)對url的獲取
static NSString * const jsGetImages =
@"function getImages(){\
var objs = document.getElementsByTagName(\"img\");\
var imgScr = '';\
for(var i=0;i<objs.length;i++){\
imgScr = imgScr + objs[i].src + '+';\
};\
return imgScr;\
};";
[webView stringByEvaluatingJavaScriptFromString:jsGetImages];//注入js方法
NSString *urlResult = [webView stringByEvaluatingJavaScriptFromString:@"getImages()"];
NSArray *urlArray = [NSMutableArray arrayWithArray:[urlResult componentsSeparatedByString:@"+"]];
//urlResurlt 就是獲取到得所有圖片的url的拼接瞎饲;mUrlArray就是所有Url的數(shù)組
}
//WKWebView
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation
{
static NSString * const jsGetImages =
@"function getImages(){\
var objs = document.getElementsByTagName(\"img\");\
var imgScr = '';\
for(var i=0;i<objs.length;i++){\
imgScr = imgScr + objs[i].src + '+';\
};\
return imgScr;\
};";
[webView evaluateJavaScript:jsGetImages completionHandler:nil];
[webView evaluateJavaScript:@"getImages()" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
NSLog(@"%@",result);
}];
}
獲取到webview的高度
CGFloat height = [[self.webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];
navigationBar變?yōu)榧兺该?/em>
//第一種方法
//導航欄純透明
[self.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
//去掉導航欄底部的黑線
self.navigationBar.shadowImage = [UIImage new];
//第二種方法
[[self.navigationBar subviews] objectAtIndex:0].alpha = 0;
navigationBar根據(jù)滑動距離的漸變色實現(xiàn)
//第一種
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
CGFloat offsetToShow = 200.0;//滑動多少就完全顯示
CGFloat alpha = 1 - (offsetToShow - scrollView.contentOffset.y) / offsetToShow;
[[self.navigationController.navigationBar subviews] objectAtIndex:0].alpha = alpha;
}
//第二種
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
CGFloat offsetToShow = 200.0;
CGFloat alpha = 1 - (offsetToShow - scrollView.contentOffset.y) / offsetToShow;
[self.navigationController.navigationBar setShadowImage:[UIImage new]];
[self.navigationController.navigationBar setBackgroundImage:[self imageWithColor:[[UIColor orangeColor]colorWithAlphaComponent:alpha]] forBarMetrics:UIBarMetricsDefault];
}
//生成一張純色的圖片
- (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 *theImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return theImage;
}
iOS 開發(fā)中一些相關的路徑
模擬器的位置:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs
文檔安裝位置:
/Applications/Xcode.app/Contents/Developer/Documentation/DocSets
插件保存路徑:
~/Library/ApplicationSupport/Developer/Shared/Xcode/Plug-ins
自定義代碼段的保存路徑:
~/Library/Developer/Xcode/UserData/CodeSnippets/
如果找不到CodeSnippets文件夾沈善,可以自己新建一個CodeSnippets文件夾乡数。
描述文件路徑
~/Library/MobileDevice/Provisioning Profiles
navigationItem的BarButtonItem如何緊靠屏幕右邊界或者左邊界?
一般情況下矮瘟,右邊的item會和屏幕右側保持一段距離:
image.png
下面是通過添加一個負值寬度的固定間距的item來解決瞳脓,也可以改變寬度實現(xiàn)不同的間隔:
UIImage *img = [[UIImage imageNamed:@"icon_cog"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//寬度為負數(shù)的固定間距的系統(tǒng)item
UIBarButtonItem *rightNegativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
[rightNegativeSpacer setWidth:-15];
UIBarButtonItem *rightBtnItem1 = [[UIBarButtonItem alloc]initWithImage:img style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonItemClicked:)];
UIBarButtonItem *rightBtnItem2 = [[UIBarButtonItem alloc]initWithImage:img style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonItemClicked:)];
self.navigationItem.rightBarButtonItems = @[rightNegativeSpacer,rightBtnItem1,rightBtnItem2];
image1.png