本文屬個人筆記,不做詳解,僅供參考!
-
解決同時按兩個按鈕進入兩個View的問題
[button setExclusiveTouch:YES];
-
在6p模擬器上輸出寬度是414,在6p真機上輸出是375。是測試機本身設置的問題,到 設置->顯示與亮度->顯示模式,改為“標準”
-
修改tableViewCell選中狀態的顏色
cell.selectedBackgroundView = [[UIView alloc] initWithFrame: cell.frame];
cell.selectedBackgroundView.backgroundColor = [UIColor whiteColor];
-
默認選中第一個cell
NSInteger selectedIndex = 0;
NSIndexPath *selectedIndexPath = [NSIndexPath indexPathForRow:selectedIndex inSection:0];
[self.tableView selectRowAtIndexPath:selectedIndexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
-
修改textFieldplaceholder字體顏色和大小
textField.placeholder = @"iOS";
[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
[textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];
-
關于右滑返回上一級
自定義leftBarButtonItem后無法啟用系統自帶的右滑返回,可以設置一下代碼:
self.navigationController.interactivePopGestureRecognizer.delegate = self;
-
取掉導航欄下邊的黑線
[self.navigationController.navigationBar setBackgroundImage: [UIImage alloc]init]];
self.navigationController.navigationBar.shadowImage = [[UIImage alloc]init];
-
點擊cell單元格的時候取消選中cell
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
-
UITextField默認顯示鍵盤
textField.becomeFirstResponder()
-
UIImage設置圓角
說到設置圓角,你是否首先想到的是:
self.iconImage.layer.cornerRadius = 20;
self.iconImage.layer.masksToBounds = YES;
建議大家盡量不要這么設置, 因為使用圖層過量會有卡頓現象, 特別是弄圓角或者陰影會很卡, 如果設置圖片圓角我們一般用繪圖來做:
/** 設置圓形圖片(放到分類中使用) */
-(UIImage *)cutCircleImage {
UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0);
// 獲取上下文
CGContextRef ctr = UIGraphicsGetCurrentContext();
// 設置圓形
CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
CGContextAddEllipseInRect(ctr, rect);
// 裁剪
CGContextClip(ctr);
// 將圖片畫上去
[self drawInRect:rect];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
這個方法就是設置圓角圖片, 效率很高, 不會造成卡頓現象, 大家要把這個方法單獨放到分類中使用
-
磁盤總空間大小
1.獲取磁盤總空間大小
//磁盤總空間
+(CGFloat)diskOfAllSizeMBytes{
CGFloat size = 0.0;
NSError *error;
NSDictionary *dic = [[NSFileManager defaultManager]attributesOfFileSystemForPath:NSHomeDirectory() error:&error];
if (error) {
#ifdef DEBUG
NSLog(@"error: %@", error.localizedDescription);
#endif
}else{
NSNumber *number = [dic objectForKey:NSFileSystemSize];
size = [number floatValue]/1024/1024;
}
return size;
}
2.獲取磁盤可用空間大小
//磁盤可用空間
+(CGFloat)diskOfFreeSizeMBytes{
CGFloat size = 0.0;
NSError *error;
NSDictionary *dic = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error];
if (error) {
#ifdef DEBUG
NSLog(@"error: %@", error.localizedDescription);
#endif
}else{
NSNumber *number = [dic objectForKey:NSFileSystemFreeSize];
size = [number floatValue]/1024/1024;
}
return size;
}
3.獲取指定路徑下某個文件的大小
//獲取文件大小
+(long long)fileSizeAtPath:(NSString *)filePath{
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:filePath]) return 0;
return [[fileManager attributesOfItemAtPath:filePath error:nil] fileSize];
}
4.獲取文件夾下所有文件的大小
//獲取文件夾下所有文件的大小
+(long long)folderSizeAtPath:(NSString *)folderPath{
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath:folderPath]) return 0;
NSEnumerator *filesEnumerator = [[fileManager subpathsAtPath:folderPath] objectEnumerator];
NSString *fileName;
long long folerSize = 0;
while ((fileName = [filesEnumerator nextObject]) != nil) {
NSString *filePath = [folderPath stringByAppendingPathComponent:fileName];
folerSize += [self fileSizeAtPath:filePath];
}
return folerSize;
}
-
NSString處理
--獲取字符串(或漢字)首字母
//獲取字符串(或漢字)首字母
+(NSString *)firstCharacterWithString:(NSString *)string{
NSMutableString *str = [NSMutableString stringWithString:string];
CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO);
CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO);
NSString *pingyin = [str capitalizedString];
return [pingyin substringToIndex:1];
}
--字符串反轉
-(NSString*)reverseWordsInString:(NSString*)str
{
NSMutableString *reverString = [NSMutableString stringWithCapacity:str.length];
[str enumerateSubstringsInRange:NSMakeRange(0, str.length) options:NSStringEnumerationReverse | NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
[reverString appendString:substring];
}];
return reverString;
}
--字符串按多個符號分割
NSString *str = @“abc,def.ghi”
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@“,.”];
NSLog(@“%@”,[str componentsSeparatedByCharactersInSet:set]);
--獲取漢字的拼音
+(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;
}
--字符串中是否含有中文
+(BOOL)checkIsChinese:(NSString *)string
{
for (int i=0; i<string.length; i++)
{
unichar ch = [string characterAtIndex:i];
if (0x4E00 <= ch && ch <= 0x9FA5)
{
return YES;
}
}
return NO;
}
-
UILabel修改行距,首行縮進
1.UILabel修改文字行距,首行縮進
lineSpacing: 行間距
firstLineHeadIndent:首行縮進
font: 字體
textColor: 字體顏色
- (NSDictionary *)settingAttributesWithLineSpacing:(CGFloat)lineSpacing FirstLineHeadIndent:(CGFloat)firstLineHeadIndent Font:(UIFont *)font TextColor:(UIColor *)textColor{
//分段樣式
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
//行間距
paragraphStyle.lineSpacing = lineSpacing;
//首行縮進
paragraphStyle.firstLineHeadIndent = firstLineHeadIndent;
//富文本樣式
NSDictionary *attributeDic = @{
NSFontAttributeName : font,
NSParagraphStyleAttributeName : paragraphStyle,
NSForegroundColorAttributeName : textColor
};
return attributeDic;
}
-
刪除NSUserDefaults所有記錄
第一種:
NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
第二種:
-(void)resetDefaults
{
NSUserDefaults * defs = [NSUserDefaults standardUserDefaults];
NSDictionary * dict = [defs dictionaryRepresentation];
for (id key in dict)
{
[defs removeObjectForKey:key];
}
[defs synchronize];
}
-
禁止鎖屏
默認情況下,當設備一段時間沒有觸控動作時,iOS會鎖住屏幕。但有一些應用是不需要鎖屏的,比如視頻播放器。
[UIApplication sharedApplication].idleTimerDisabled = YES;
或
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];
-
隱藏/顯示文件
//顯示
defaults write com.apple.finder AppleShowAllFiles -bool true
killall Finder
//隱藏
defaults write com.apple.finder AppleShowAllFiles -bool false
killall Finder
-
iOS跳轉到App Store下載應用評分
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=APPID"]];
-
iOS在當前屏幕獲取第一響應
UIWindow * keyWindow = [[UIApplication sharedApplication] keyWindow];
UIView * firstResponder = [keyWindow performSelector:@selector(firstResponder)];
-
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);
-
關于NSDateFormatter的格式
G: 公元時代,例如AD公元
yy: 年的后2位
yyyy: 完整年
MM: 月,顯示為1-12
MMM: 月,顯示為英文月份簡寫,如 Jan
MMMM: 月,顯示為英文月份全稱,如 Janualy
dd: 日,2位數表示,如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: 毫秒
-
阿拉伯數字轉中文格式
+(NSString *)translation:(NSString *)arebic
{
NSString *str = arebic;
NSArray *arabic_numerals = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"0"];
NSArray *chinese_numerals = @[@"一",@"二",@"三",@"四",@"五",@"六",@"七",@"八",@"九",@"零"];
NSArray *digits = @[@"個",@"十",@"百",@"千",@"萬",@"十",@"百",@"千",@"億",@"十",@"百",@"千",@"兆"];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:chinese_numerals forKeys:arabic_numerals];
NSMutableArray *sums = [NSMutableArray array];
for (int i = 0; i < str.length; i ++) {
NSString *substr = [str substringWithRange:NSMakeRange(i, 1)];
NSString *a = [dictionary objectForKey:substr];
NSString *b = digits[str.length -i-1];
NSString *sum = [a stringByAppendingString:b];
if ([a isEqualToString:chinese_numerals[9]])
{
if([b isEqualToString:digits[4]] || [b isEqualToString:digits[8]])
{
sum = b;
if ([[sums lastObject] isEqualToString:chinese_numerals[9]])
{
[sums removeLastObject];
}
}else
{
sum = chinese_numerals[9];
}
if ([[sums lastObject] isEqualToString:sum])
{
continue;
}
}
[sums addObject:sum];
}
NSString *sumStr = [sums componentsJoinedByString:@""];
NSString *chinese = [sumStr substringToIndex:sumStr.length-1];
NSLog(@"%@",str);
NSLog(@"%@",chinese);
return chinese;
}
-
CocoaPods pod install/pod update更新慢的問題
pod install --verbose --no-repo-update
pod update --verbose --no-repo-update
如果不加后面的參數,默認會升級CocoaPods的spec倉庫,加一個參數可以省略這一步,然后速度就會提升不少
-
UIView設置部分圓角
你是不是也遇到過這樣的問題,一個button或者label,只要右邊的兩個角圓角,或者只要一個圓角。該怎么辦呢。這就需要圖層蒙版來幫助我們了
CGRect rect = view.bounds;
CGSize radio = CGSizeMake(30, 30);//圓角尺寸
UIRectCorner corner = UIRectCornerTopLeft|UIRectCornerTopRight;//這只圓角位置
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:corner cornerRadii:radio];
CAShapeLayer *masklayer = [[CAShapeLayer alloc]init];//創建shapelayer
masklayer.frame = view.bounds;
masklayer.path = path.CGPath;//設置路徑
view.layer.mask = masklayer;
-
取上整與取下整
floor(x),有時候也寫做Floor(x),其功能是“下取整”,即取不大于x的最大整數 例如:
x=3.14,floor(x)=3
y=9.99999,floor(y)=9
與floor函數對應的是ceil函數,即上取整函數。
ceil函數的作用是求不小于給定實數的最小整數。
ceil(2)=ceil(1.2)=cei(1.5)=2.00
floor函數與ceil函數的返回值均為double型
-
去掉導航欄返回的back標題
[[UIBarButtonItemappearance]setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)forBarMetrics:UIBarMetricsDefault];
-
navigationBar變為純透明
//第一種方法
//導航欄純透明
[self.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
//去掉導航欄底部的黑線
self.navigationBar.shadowImage = [UIImage new];
//第二種方法
[[self.navigationBar subviews] objectAtIndex:0].alpha = 0;
-
tabBar同理
[self.tabBar setBackgroundImage:[UIImage new]];
self.tabBar.shadowImage = [UIImage new];
-
navigationBar根據滑動距離的漸變色實現
第一種:
-(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開發中一些相關的路徑
模擬器的位置:
/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
-
dispatch_group的使用
dispatch_group_t dispatchGroup = dispatch_group_create();
dispatch_group_enter(dispatchGroup);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSLog(@"第一個請求完成");
dispatch_group_leave(dispatchGroup);
});
dispatch_group_enter(dispatchGroup);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSLog(@"第二個請求完成");
dispatch_group_leave(dispatchGroup);
});
dispatch_group_notify(dispatchGroup, dispatch_get_main_queue(), ^(){
NSLog(@"請求完成");
});