iOS開發(fā)技巧
一做盅、調(diào)用代碼使APP進入后臺,達到點擊Home鍵的效果分扎。(私有API)
[[UIApplication sharedApplication] performSelector:@selector(suspend)];
suspend的英文意思有:暫停; 懸; 掛; 延緩;
二澄成、帶有中文的URL處理。
大概舉個例子畏吓,類似下面的URL墨状,里面直接含有中文,可能導致播放不了菲饼,那么我們要處理一個這個URL肾砂,因為他太操蛋了,居然用中文宏悦。
http://static.tripbe.com/videofiles/視頻/我的自拍視頻.mp4
NSString *path = (__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (__bridge CFStringRef)model.mp4_url,CFSTR(""),CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
三镐确、獲取UIWebView的高度
個人最常用的獲取方法,感覺這個比較靠譜
- (void)webViewDidFinishLoad:(UIWebView *)webView {
CGFloat height = [[webView stringByEvaluatingJavaScriptFromString:@"document.body.offsetHeight"] floatValue];
CGRect frame = webView.frame;
webView.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, height);
}
四肛根、給UIView設置圖片(UILabel一樣適用)
第一種方法:
利用的UIView的設置背景顏色方法辫塌,用圖片做圖案顏色漏策,然后傳給背景顏色派哲。
UIColor *bgColor = [UIColor colorWithPatternImage: [UIImage imageNamed:@"bgImg.png"];
UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0,0,320,480)];
[myView setBackGroundColor:bgColor];
第二種方法:
UIImage *image = [UIImage imageNamed:@"yourPicName@2x.png"];
yourView.layer.contents = (__bridge id)image.CGImage;
//設置顯示的圖片范圍
yourView.layer.contentsCenter = CGRectMake(0.25,0.25,0.5,0.5);//四個值在0-1之間,對應的為x掺喻,y芭届,width,height感耙。
五褂乍、去掉UITableView多余的分割線
yourTableView.tableFooterView = [UIView new];
六、調(diào)整cell分割線的位置即硼,兩個方法一起用逃片,暴力解決,防脫發(fā)
-(void)viewDidLayoutSubviews {
if ([self.mytableview respondsToSelector:@selector(setSeparatorInset:)]) {
[self.mytableview setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
}
if ([self.mytableview respondsToSelector:@selector(setLayoutMargins:)]) {
[self.mytableview setLayoutMargins:UIEdgeInsetsMake(0, 0, 0, 0)];
}
}
#pragma mark - cell分割線
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
[cell setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
}
if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
[cell setLayoutMargins:UIEdgeInsetsMake(0, 0, 0, 0)];
}
}
七只酥、UILabel和UIImageView的交互userInteractionEabled默認為NO褥实。
那么如果你把這兩個類做為父試圖的話呀狼,里面的所有東東都不可以點擊哦。曾經(jīng)有一個人损离,讓我?guī)兔φ{(diào)試bug哥艇,他調(diào)試很久沒搞定,就是把WMPlayer對象(播放器對象)放到一個UIImageView上面僻澎。這樣imageView addSubView:wmPlayer后貌踏,播放器的任何東東都不能點擊了。userInteractionEabled設置為YES即可窟勃。
八祖乳、UISearchController和UISearchBar的Cancle按鈕改title問題,簡單粗暴
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
searchController.searchBar.showsCancelButton = YES;
UIButton *canceLBtn = [searchController.searchBar valueForKey:@"cancelButton"];
[canceLBtn setTitle:@"取消" forState:UIControlStateNormal];
[canceLBtn setTitleColor:[UIColor colorWithRed:14.0/255.0 green:180.0/255.0 blue:0.0/255.0 alpha:1.00] forState:UIControlStateNormal];
searchBar.showsCancelButton = YES;
return YES;
}
九秉氧、UITableView收起鍵盤何必這么麻煩
一個屬性搞定凡资,效果好(UIScrollView同樣可以使用)
以前是不是覺得[self.view endEditing:YES];很屌,這個下面的更屌谬运。
yourTableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
另外一個枚舉為UIScrollViewKeyboardDismissModeInteractive隙赁,表示在鍵盤內(nèi)部滑動,鍵盤逐漸下去梆暖。
十伞访、NSTimer
1、NSTimer計算的時間并不精確
2轰驳、NSTimer需要添加到runLoop運行才會執(zhí)行厚掷,但是這個runLoop的線程必須是已經(jīng)開啟。
3级解、NSTimer會對它的tagert進行retain冒黑,我們必須對其重復性的使用intvailte停止。target如果是self(指UIViewController)勤哗,那么VC的retainCount+1抡爹,如果你不釋放NSTimer,那么你的VC就不會dealloc了芒划,內(nèi)存泄漏了冬竟。
十一、IOS編譯報錯:objc-class-ref in AppDelegate.o之解決方案 Xcode7
Undefined symbols for architecture x86_64:
"_OBJC_CLASS_$_QQApiInterface", referenced from:
objc-class-ref in AppDelegate.o
"_OBJC_CLASS_$_ShareSDK", referenced from:
objc-class-ref in AppDelegate.o
objc-class-ref in RecipeDetailViewController.o
objc-class-ref in showViewController.o
objc-class-ref in video_show.o
"_OBJC_CLASS_$_TencentOAuth", referenced from:
objc-class-ref in AppDelegate.o
"_OBJC_CLASS_$_WXApi", referenced from:
objc-class-ref in AppDelegate.o
![](http://upload-images.jianshu.io/upload_images/2069363-f62503c612499d5a?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
1.把1.選中Targets—>Build Settings—>Architectures民逼。
把build active architectures only 改為 NO泵殴。
2. 把最下面的Valid Architectures中的arm64參數(shù)刪掉就可以了
或者:
雙擊Architectures,選擇other拼苍,刪除$(ARCH_STANDARD)笑诅,然后增加armv7和armv7s(寫上:$(ARCHS_STANDARD_32_BIT))。
3.clean 再build。
結(jié)果設置如下圖:
![](http://upload-images.jianshu.io/upload_images/2069363-fc39f2b565a7b99d?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
目前設置完成后吆你,問題順利解決同蜻,大家有更好的解決方案,歡迎討論早处!
十二湾蔓、用十六進制獲取UIColor(類方法或者Category都可以,這里我用工具類方法)
+ (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];
}
// strip 0X if it appears
if ([cString hasPrefix:@"0X"])
cString = [cString substringFromIndex:2];
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:1.0f];
}
十三砌梆、獲取今天是星期幾
+ (NSString *) getweekDayStringWithDate:(NSDate *) date
{
NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; // 指定日歷的算法
NSDateComponents *comps = [calendar components:NSWeekdayCalendarUnit fromDate:date];
// 1 是周日默责,2是周一 3.以此類推
NSNumber * weekNumber = @([comps weekday]);
NSInteger weekInt = [weekNumber integerValue];
NSString *weekDayString = @"(周一)";
switch (weekInt) {
case 1:
{
weekDayString = @"(周日)";
}
break;
case 2:
{
weekDayString = @"(周一)";
}
break;
case 3:
{
weekDayString = @"(周二)";
}
break;
case 4:
{
weekDayString = @"(周三)";
}
break;
case 5:
{
weekDayString = @"(周四)";
}
break;
case 6:
{
weekDayString = @"(周五)";
}
break;
case 7:
{
weekDayString = @"(周六)";
}
break;
default:
break;
}
return weekDayString;
}
十四、UIView的部分圓角問題
UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(120, 10, 80, 80)];
view2.backgroundColor = [UIColor redColor];
[self.view addSubview:view2];
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view2.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(10, 10)];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = view2.bounds;
maskLayer.path = maskPath.CGPath;
view2.layer.mask = maskLayer;
//其中咸包,
byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight
//指定了需要成為圓角的角桃序。該參數(shù)是UIRectCorner類型的,可選的值有:
* UIRectCornerTopLeft
* UIRectCornerTopRight
* UIRectCornerBottomLeft
* UIRectCornerBottomRight
* UIRectCornerAllCorners
從名字很容易看出來代表的意思烂瘫,使用“|”來組合就好了媒熊。
十五、設置滑動的時候隱藏navigationBar
navigationController.hidesBarsOnSwipe = Yes;
十六坟比、iOS畫虛線
記得先 QuartzCore框架的導入
#import
CGContextRef context =UIGraphicsGetCurrentContext();
CGContextBeginPath(context);
CGContextSetLineWidth(context, 2.0);
CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor);
CGFloat lengths[] = {10,10};
CGContextSetLineDash(context, 0, lengths,2);
CGContextMoveToPoint(context, 10.0, 20.0);
CGContextAddLineToPoint(context, 310.0,20.0);
CGContextStrokePath(context);
CGContextClosePath(context);
十七芦鳍、自動布局中多行UILabel,需要設置其
preferredMaxLayoutWidth屬性才能正常顯示多行內(nèi)容葛账。另外如果出現(xiàn)顯示不全文本柠衅,可以在計算的結(jié)果基礎上+0.5。
CGFloat h = [model.message boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width - kGAP-kAvatar_Size - 2*kGAP, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.height+0.5;
十八籍琳、 禁止程序運行時自動鎖屏
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];
十九菲宴、KVC相關(guān),支持操作符
KVC同時還提供了很復雜的函數(shù)趋急,主要有下面這些
①簡單集合運算符
簡單集合運算符共有@avg喝峦, @count , @max 呜达, @min 谣蠢,@sum5種,都表示啥不用我說了吧闻丑, 目前還不支持自定義漩怎。
@interface Book : NSObject
@property (nonatomic,copy) NSString* name;
@property (nonatomic,assign) CGFloat price;
@end
@implementation Book
@end
Book *book1 = [Book new];
book1.name = @"The Great Gastby";
book1.price = 22;
Book *book2 = [Book new];
book2.name = @"Time History";
book2.price = 12;
Book *book3 = [Book new];
book3.name = @"Wrong Hole";
book3.price = 111;
Book *book4 = [Book new];
book4.name = @"Wrong Hole";
book4.price = 111;
NSArray* arrBooks = @[book1,book2,book3,book4];
NSNumber* sum = [arrBooks valueForKeyPath:@"@sum.price"];
NSLog(@"sum:%f",sum.floatValue);
NSNumber* avg = [arrBooks valueForKeyPath:@"@avg.price"];
NSLog(@"avg:%f",avg.floatValue);
NSNumber* count = [arrBooks valueForKeyPath:@"@count"];
NSLog(@"count:%f",count.floatValue);
NSNumber* min = [arrBooks valueForKeyPath:@"@min.price"];
NSLog(@"min:%f",min.floatValue);
NSNumber* max = [arrBooks valueForKeyPath:@"@max.price"];
NSLog(@"max:%f",max.floatValue);
打印結(jié)果
2016-04-20 16:45:54.696 KVCDemo[1484:127089] sum:256.000000
2016-04-20 16:45:54.697 KVCDemo[1484:127089] avg:64.000000
2016-04-20 16:45:54.697 KVCDemo[1484:127089] count:4.000000
2016-04-20 16:45:54.697 KVCDemo[1484:127089] min:12.000000
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);
二十、系統(tǒng)和電池詳情
?- (void)viewDidLoad {
[super viewDidLoad];
[self showBatteryInfo];
[self showDeviceInfo];
// 檢測電池信息
[UIDevice currentDevice].batteryMonitoringEnabled = YES;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showDeviceInfo) name:UIDeviceBatteryStateDidChangeNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showBatteryInfo) name:UIDeviceBatteryLevelDidChangeNotification object:nil];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)showDeviceInfo
{
UIDevice *device = [UIDevice currentDevice];
NSString *msg = [NSString stringWithFormat:@"系統(tǒng)信息:\n模式:%@\n名字:%@\n系統(tǒng)名:%@\n系統(tǒng)的版本:%@",device.localizedModel,device.name,device.systemName,device.systemVersion];
NSLog(@"%@",msg);
self.systemInfoLabel.text = msg;
}
- (void)showBatteryInfo
{
UIDevice *device = [UIDevice currentDevice];
NSString *msg = [NSString stringWithFormat:@"電池的狀態(tài):%li\n電量:%.2f",(long)device.batteryState,device.batteryLevel];
NSLog(@"%@",msg);
self.batteryInfo.text = msg;
}
二十一嗦嗡、強制讓App直接退出(非閃退,非崩潰)
- (void)exitApplication {
AppDelegate *app = [UIApplication sharedApplication].delegate;
UIWindow *window = app.window;
[UIView animateWithDuration:1.0f animations:^{
window.alpha = 0;
} completion:^(BOOL finished) {
exit(0);
}];
}
二十二饭玲、Label行間距
NSMutableAttributedString *attributedString =
[[NSMutableAttributedString alloc] initWithString:self.contentLabel.text];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:3];
//調(diào)整行間距
[attributedString addAttribute:NSParagraphStyleAttributeName
value:paragraphStyle
range:NSMakeRange(0, [self.contentLabel.text length])];
self.contentLabel.attributedText = attributedString;
二十三侥祭、CocoaPods pod install/pod update更新慢的問題
pod install –verbose –no-repo-update
pod update –verbose –no-repo-update
如果不加后面的參數(shù),默認會升級CocoaPods的spec倉庫,加一個參數(shù)可以省略這一步矮冬,然后速度就會提升不少谈宛。
二十四、MRC和ARC混編設置方式
在XCode中targets的build phases選項下Compile Sources下選擇 不需要arc編譯的文件
雙擊輸入 -fno-objc-arc 即可
MRC工程中也可以使用ARC的類胎署,方法如下:
在XCode中targets的build phases選項下Compile Sources下選擇要使用arc編譯的文件
雙擊輸入 -fobjc-arc 即可
二十五吆录、把tableview里cell的小對勾的顏色改成別的顏色
_yourTableView.tintColor = [UIColor redColor];
二十六、解決同時按兩個按鈕進兩個view的問題
[button setExclusiveTouch:YES];
二十七琼牧、修改textFieldplaceholder字體顏色和大小
textField.placeholder = @"請輸入用戶名";
[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
[textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];
二十八恢筝、禁止textField和textView的復制粘貼菜單
這里有一個誤區(qū),很多同學直接使用UITextField巨坊,然后在VC里面寫這個方法撬槽,返回NO,沒效果趾撵。怎么搞都不行侄柔,但是如果用UIPasteboard的話,項目中所有的編輯框都不能復制黏貼了占调,真操蛋暂题。
我們要做的是新建一個類MyTextField繼承UITextField,然后在MyTextField的.m文件里重寫這個方法究珊,就可以單獨控制某個輸入框了敢靡。
-(BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
if ([UIMenuController sharedMenuController]) {
[UIMenuController sharedMenuController].menuVisible = NO;
}
return NO;
}
二十九:如何進入我的軟件在app store 的頁面
先用iTunes Link Maker找到軟件在訪問地址,格式為itms-apps://ax.itunes.apple.com/…苦银,然后
#define ITUNESLINK @"itms-apps://ax.itunes.apple.com/..."
NSURL *url = [NSURL URLWithString:ITUNESLINK];
if([[UIApplication sharedApplication] canOpenURL:url]){
[[UIApplication sharedApplication] openURL:url];
}
如果把上述地址中itms-apps改為http就可以在瀏覽器中打開了啸胧。可以把這個地址放在自己的網(wǎng)站里幔虏,鏈接到app store纺念。
iTunes Link Maker地址:[http://itunes.apple.com/linkmaker](http://itunes.apple.com/linkmaker)
三十、二級三級頁面隱藏系統(tǒng)tabbar
1想括、單個處理
YourViewController *yourVC = [YourViewController new];
yourVC.hidesBottomBarWhenPushed = YES;
[self.navigationController pushViewController:yourVC animated:YES];
2.統(tǒng)一在基類里面處理
新建一個類BaseNavigationController繼承UINavigationController陷谱,然后重寫 -(void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated這個方法。所有的push事件都走此方法瑟蜈。
@interface BaseNavigationController : UINavigationController
@end
-(void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated{
[super pushViewController:viewController animated:animated];
if (self.viewControllers.count>1) {
viewController.hidesBottomBarWhenPushed = YES;
}
}
三十一烟逊、取消系統(tǒng)的返回手勢
self.navigationController.interactivePopGestureRecognizer.enabled = NO;
三十二、修改UIWebView中字體的大小铺根,顏色
1宪躯、UIWebView設置字體大小,顏色位迂,字體:
UIWebView無法通過自身的屬性設置字體的一些屬性访雪,只能通過html代碼進行設置
在webView加載完畢后详瑞,在
- (void)webViewDidFinishLoad:(UIWebView *)webView方法中加入js代碼
NSString *str = @"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '60%'";
[_webView stringByEvaluatingJavaScriptFromString:str];
或者加入以下代碼
NSString *jsString = [[NSString alloc] initWithFormat:@"document.body.style.fontSize=%f;document.body.style.color=%@",fontSize,fontColor];
[webView stringByEvaluatingJavaScriptFromString:jsString];
三十三、NSString處理技巧
使用場景舉例:可以用在處理用戶用戶輸入在UITextField的文本
//待處理的字符串
NSString *string = @" A B CD EFG\n MN\n";
//字符串替換臣缀,處理后的string1 = @"ABCDEF\nMN\n";
NSString *string1 = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
//去除兩端空格(注意是兩端),處理后的string2 = @"A B CD EFG\n MN\n";
NSString *string2 = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
//去除兩端回車(注意是兩端),處理后的string3 = @" A B CD EFG\n MN";
NSString *string3 = [string stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
//去除兩端空格和回車(注意是兩端),處理后的string4 = @"A B CD EFG\n MN";
NSString *string4 = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
三十四坝橡、主線程操作UI(對UI進行更新只能在主線程進行)
解釋:所謂的在主線程更新UI、操作UI精置,大致的意思就是設置UILabel的text或者設置tabbar的badgeValue计寇,設置UIImageView的image等等。
回到主線程方式1:
[self performSelectorOnMainThread:@selector(updateImage:) withObject:data waitUntilDone:YES];
performSelectorOnMainThread方法是NSObject的分類方法脂倦,每個NSObject對象都有此方法番宁,
它調(diào)用的selector方法是當前調(diào)用控件的方法,例如使用UIImageView調(diào)用的時候selector就是UIImageView的方法
Object:代表調(diào)用方法的參數(shù),不過只能傳遞一個參數(shù)(如果有多個參數(shù)請使用對象進行封裝)
waitUntilDone:是否線程任務完成執(zhí)行
回到主線程方式2:
dispatch_async(dispatch_get_main_queue(), ^{
//更新UI的代碼
});
這個不多解釋狼讨,GCD的方法贝淤,注意不要在主線程掉用。
三十五政供、判斷模擬器
if (TARGET_IPHONE_SIMULATOR) {
NSLog(@"是模擬器");
}else{
NSLog(@"不是模擬器");
}
三十六播聪、真機測試報 TCWeiboSDK 93 duplicate symbols for architecture armv7
這是因為在項目中引用的兩個相同的類庫引起了,在我的項目中是因為引入的兩個不同指令集引起的布隔;
三十七离陶、AFnetWorking報”Request failed: unacceptable
content-type: text/html”錯誤
AFURLResponseSerialization.m文件設置
self.acceptableContentTypes = [NSSetsetWithObjects:@"application/json", @"text/html",@"text/json",@"text/javascript", nil];
加上@”text/html”,部分,其實就是添加一種服務器返回的數(shù)據(jù)格式衅檀。
三十八招刨、隱藏navigation跳轉(zhuǎn)后的返回按鈕
//隱藏頭部左邊的返回
self.navigationItem.hidesBackButton=YES;
三十九、兩種方法刪除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];
}
四十哀军、UITableView設置Section間距
在使用UITableViewStyleGrouped類型的UITableView的時候沉眶,經(jīng)常很奇怪的出現(xiàn)多余的section間距,那可能是因為你只設置了footer或者header的間距中的其中一個杉适,那么另一個默認為20個高度谎倔,只需要設置返回0.001的CGFlot的浮點數(shù)就可以解決這個多余的間距。
//Header底部間距
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 40;//section頭部高度
}
//footer底部間距
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
return 0.001;
}
四十一猿推、NSLog 輸出格式集合
? %@ 對象
? %d, %i 整數(shù)
? %u 無符整形
? %f 浮點/雙字
? %x, %X 二進制整數(shù)
? %o 八進制整數(shù)
? %zu size_t
? %p 指針
? %e 浮點/雙字 (科學計算)
? %g 浮點/雙字
? %s C 字符串
? %.*s Pascal字符串
? %c 字符
? %C unichar
? %lld 64位長整數(shù)(long long)
? %llu 無符64位長整數(shù)
%Lf 64位雙字
四十二片习、常用GCD總結(jié)
為了方便地使用GCD,蘋果提供了一些方法方便我們將block放在主線程 或 后臺線程執(zhí)行蹬叭,或者延后執(zhí)行藕咏。使用的例子如下:
// 后臺執(zhí)行:
dispatch_async(dispatch_get_global_queue(0, 0), ^{
// something
});
// 主線程執(zhí)行:
dispatch_async(dispatch_get_main_queue(), ^{
// something
});
// 一次性執(zhí)行:
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// code to be executed once
});
// 延遲2秒執(zhí)行:
double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
// code to be executed on the main queue after delay
});
dispatch_queue_t 也可以自己定義,如要要自定義queue秽五,可以用dispatch_queue_create方法孽查,示例如下:
dispatch_queue_t urls_queue = dispatch_queue_create("blog.devtang.com", NULL);
dispatch_async(urls_queue, ^{
// your code
});
dispatch_release(urls_queue);
另外,GCD還有一些高級用法筝蚕,例如讓后臺2個線程并行執(zhí)行卦碾,然后等2個線程都結(jié)束后铺坞,再匯總執(zhí)行結(jié)果起宽。這個可以用dispatch_group, dispatch_group_async 和 dispatch_group_notify來實現(xiàn)洲胖,示例如下:
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, dispatch_get_global_queue(0,0), ^{
// 并行執(zhí)行的線程一
});
dispatch_group_async(group, dispatch_get_global_queue(0,0), ^{
// 并行執(zhí)行的線程二
});
dispatch_group_notify(group, dispatch_get_global_queue(0,0), ^{
// 上面的線程走完成后,最后通知走次block坯沪,保證這部分代碼最后執(zhí)行
});
四十三绿映、 iOS中的隨機數(shù)
生成0-x之間的隨機正整數(shù)
int value =arc4random_uniform(x + 1);
生成隨機正整數(shù)
int value = arc4random()
通過arc4random() 獲取0到x-1之間的整數(shù)的代碼如下:
int value = arc4random() % x;
獲取1到x之間的整數(shù)的代碼如下:
int value = (arc4random() % x) + 1;
最后如果想生成一個浮點數(shù),可以在項目中定義如下宏:
#define ARC4RANDOM_MAX 0x100000000
然后就可以使用arc4random() 來獲取0到100之間浮點數(shù)了(精度是rand()的兩倍)腐晾,代碼如下:
double val = floorf(((double)arc4random() / ARC4RANDOM_MAX) * 100.0f);
四十四叉弦、系統(tǒng)自帶的UITableViewCell,其中cell.accessoryView可以自定義控件
if (indexPath.section == 2 && indexPath.row == 0) {
cell.accessoryView = [[UISwitch alloc] init];
} else {
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
四十五藻糖、isKindOfClass, isMemberOfClass的用法區(qū)分
-(BOOL) isKindOfClass: classObj判斷是否是這個類或者這個類的子類的實例
-(BOOL) isMemberOfClass: classObj 判斷是否是這個類的實例
實例一:
Person *person = [[Person alloc] init]; //父類
Teacher *teacher = [[Teacher alloc] init]; //子類
//YES
if ([teacher isMemberOfClass:[Teacher class]]) {
NSLog(@"teacher Teacher類的成員");
}
//NO
if ([teacher isMemberOfClass:[Person class]]) {
NSLog(@"teacher Person類的成員");
}
//NO
if ([teacher isMemberOfClass:[NSObject class]]) {
NSLog(@"teacher NSObject類的成員");
}
實例二:
Person *person = [[Person alloc] init];
Teacher *teacher = [[Teacher alloc] init];
//YES
if ([teacher isKindOfClass:[Teacher class]]) {
NSLog(@"teacher 是 Teacher類或Teacher的子類");
}
//YES
if ([teacher isKindOfClass:[Person class]]) {
NSLog(@"teacher 是 Person類或Person的子類");
}
//YES
if ([teacher isKindOfClass:[NSObject class]]) {
NSLog(@"teacher 是 NSObject類或NSObject的子類");
}
isMemberOfClass判斷是否是屬于這類的實例淹冰,是否跟父類有關(guān)系他不管,所以isMemberOfClass指到父類時才會為NO;
四十六、關(guān)于UIScreen
UIScreen對象包含了整個屏幕的邊界矩形巨柒。當構(gòu)造應用的用戶界面接口時樱拴,你應該使用該對象的屬性來獲得推薦的矩形大小,用以構(gòu)造你的程序窗口洋满。
CGRect bound = [[UIScreen mainScreen] bounds]; // 返回的是帶有狀態(tài)欄的Rect
CGRect frame = [[UIScreen mainScreen] applicationFrame]; // 返回的是不帶有狀態(tài)欄的Rect
float scale = [[UIScreen mainScreen] scale]; // 得到設備的自然分辨率
對于scale屬性需要做進一步的說明:
以前的iphone 設備屏幕分辨率都是320*480晶乔,后來apple 在iPhone 4中采用了名為Retina的顯示技術(shù),iPhone
4采用了960x640像素分辨率的顯示屏幕牺勾。由于屏幕大小沒有變正罢,還是3.5英寸,分辨率的提升將iPhone 4的顯示分辨率提升至iPhone
3GS的四倍驻民,每英寸的面積里有326個像素翻具。
scale屬性的值有兩個:
scale = 1; 的時候是代表當前設備是320*480的分辨率(就是iphone4之前的設備)
scale = 2; 的時候是代表分辨率為640*960的分辨率
// 判斷屏幕類型,普通還是視網(wǎng)膜
float scale = [[UIScreen mainScreen] scale];
if (scale == 1) {
bIsRetina = NO;
NSLog(@"普通屏幕");
}else if (scale == 2) {
bIsRetina = YES;
NSLog(@"視網(wǎng)膜屏幕");
}else{
NSLog(@"unknow screen mode !");
}
四十七回还、UIView的clipsTobounds屬性
view2添加view1到中裆泳,如果view2大于view1,或者view2的坐標不全在view1的范圍內(nèi)懦趋,view2是蓋著view1的晾虑,意思就是超出的部份也會畫出來,UIView有一個屬性,clipsTobounds 默認情況下是NO仅叫。如果帜篇,我們想要view2把超出的那部份現(xiàn)實出來,就得改變它的父視圖也就view1的clipsTobounds屬性值诫咱。view1.clipsTobounds = YES;
可以很好地解決覆蓋的問題
四十八笙隙、百度坐標跟火星坐標相互轉(zhuǎn)換
//百度轉(zhuǎn)火星坐標
+ (CLLocationCoordinate2D )bdToGGEncrypt:(CLLocationCoordinate2D)coord
{
double x = coord.longitude - 0.0065, y = coord.latitude - 0.006;
double z = sqrt(x * x + y * y) - 0.00002 * sin(y * M_PI);
double theta = atan2(y, x) - 0.000003 * cos(x * M_PI);
CLLocationCoordinate2D transformLocation ;
transformLocation.longitude = z * cos(theta);
transformLocation.latitude = z * sin(theta);
return transformLocation;
}
//火星坐標轉(zhuǎn)百度坐標
+ (CLLocationCoordinate2D )ggToBDEncrypt:(CLLocationCoordinate2D)coord
{
double x = coord.longitude, y = coord.latitude;
double z = sqrt(x * x + y * y) + 0.00002 * sin(y * M_PI);
double theta = atan2(y, x) + 0.000003 * cos(x * M_PI);
CLLocationCoordinate2D transformLocation ;
transformLocation.longitude = z * cos(theta) + 0.0065;
transformLocation.latitude = z * sin(theta) + 0.006;
return transformLocation;
}
四十九、繪制1像素的線
#define SINGLE_LINE_WIDTH (1 / [UIScreen mainScreen].scale)
#define SINGLE_LINE_ADJUST_OFFSET ((1 / [UIScreen mainScreen].scale) / 2)
代碼如下:
UIView *view = [[UIView alloc] initWithFrame:CGrect(x - SINGLE_LINE_ADJUST_OFFSET, 0, SINGLE_LINE_WIDTH, 100)];
注意:如果線寬為偶數(shù)Point的話坎缭,則不要去設置偏移竟痰,否則線條也會失真
五十签钩、UILabel顯示HTML文本(IOS7以上)
NSString * htmlString = @" Some html string \n This is some text! ";
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];
五十一、添加pch文件的步聚
1:創(chuàng)建新文件 ios->other->PCH file坏快,創(chuàng)建一個pch文件:“工程名-Prefix.pch”:
2:將building setting中的precompile header選項的路徑添加“$(SRCROOT)/項目名稱/pch文件名”(例如:$(SRCROOT)/LotteryFive/LotteryFive-Prefix.pch)
3:將Precompile Prefix Header為YES铅檩,預編譯后的pch文件會被緩存起來,可以提高編譯速度
五十二莽鸿、兼容字體大小6plue跟它以下的區(qū)別
#define FONT_COMPATIBLE_SCREEN_OFFSET(_fontSize_) [UIFont systemFontOfSize:(_fontSize_ *([UIScreen mainScreen].scale) / 2)]
在iPhone4~6中昧旨,縮放因子scale=2;在iPhone6+中祥得,縮放因子scale=3
運用時:
myLabel.font=FONT_COMPATIBLE_SCREEN_OFFSET(15);
五十三兔沃、APP虛擬器可以運行,在真機調(diào)試時報這個問題级及,因為把項目名稱設成中文導致
App installation failed
There was an internal API error.
Build Settings中的Packaging的Product Name設置成中文
五十四乒疏、關(guān)于Masonry
a:make.equalTo 或 make.greaterThanOrEqualTo (至多) 或 make.lessThanOrEqualTo(至少)
make.left.greaterThanOrEqualTo(label);
make.left.greaterThanOrEqualTo(label.mas_left);
//width >= 200 && width <= 400
make.width.greaterThanOrEqualTo(@200);
make.width.lessThanOrEqualTo(@400)
b:masequalTo 和 equalTo 區(qū)別:masequalTo 比equalTo多了類型轉(zhuǎn)換操作,一般來說饮焦,大多數(shù)時候兩個方法都是 通用的怕吴,但是對于數(shù)值元素使用mas_equalTo。對于對象或是多個屬性的處理追驴,使用equalTo械哟。特別是多個屬性時,必須使用equalTo
c:一些簡便賦值
// make top = superview.top + 5, left = superview.left + 10,
// bottom = superview.bottom - 15, right = superview.right - 20
make.edges.equalTo(superview).insets(UIEdgeInsetsMake(5, 10, 15, 20))
// make width and height greater than or equal to titleLabel
make.size.greaterThanOrEqualTo(titleLabel)
// make width = superview.width + 100, height = superview.height - 50
make.size.equalTo(superview).sizeOffset(CGSizeMake(100, -50))
// make centerX = superview.centerX - 5, centerY = superview.centerY + 10
make.center.equalTo(superview).centerOffset(CGPointMake(-5, 10))
d:and關(guān)鍵字運用
make.left.right.and.bottom.equalTo(superview);
make.top.equalTo(otherView);
e:優(yōu)先殿雪;優(yōu)先權(quán)(.priority,.priorityHigh,.priorityMedium,.priorityLow)
.priority允許您指定一個確切的優(yōu)先級
.priorityHigh 等價于UILayoutPriorityDefaultHigh
.priorityMedium 介于高跟低之間
.priorityLow 等價于UILayoutPriorityDefaultLow
實例:
make.left.greaterThanOrEqualTo(label.mas_left).with.priorityLow();
make.top.equalTo(label.mas_top).with.priority(600);
g:使用mas_makeConstraints創(chuàng)建constraint后暇咆,你可以使用局部變量或?qū)傩詠肀4嬉员阆麓我盟蝗绻麆?chuàng)建多個constraints丙曙,你可以采用數(shù)組來保存它們
// 局部或者全局
@property (nonatomic, strong) MASConstraint *topConstraint;
// 創(chuàng)建約束并賦值
[view1 mas_makeConstraints:^(MASConstraintMaker *make) {
self.topConstraint = make.top.equalTo(superview.mas_top).with.offset(padding.top);
make.left.equalTo(superview.mas_left).with.offset(padding.left);
}];
// 過后可以直接訪問self.topConstraint
[self.topConstraint uninstall];
h:mas_updateConstraints更新約束爸业,有時你需要更新constraint(例如,動畫和調(diào)試)而不是創(chuàng)建固定constraint亏镰,可以使用mas_updateConstraints方法
- (void)updateConstraints {
[self.growingButton mas_updateConstraints:^(MASConstraintMaker *make) {
make.center.equalTo(self);
make.width.equalTo(@(self.buttonSize.width)).priorityLow();
make.height.equalTo(@(self.buttonSize.height)).priorityLow();
make.width.lessThanOrEqualTo(self);
make.height.lessThanOrEqualTo(self);
}];
//調(diào)用父updateConstraints
[super updateConstraints];
}
i:mas_remakeConstraints更新約束扯旷,mas_remakeConstraints與mas_updateConstraints比較相似,都是更新constraint索抓。不過钧忽,mas_remakeConstraints是刪除之前constraint,然后再添加新的constraint(適用于移動動畫)逼肯;而mas_updateConstraints只是更新constraint的值耸黑。
- (void)changeButtonPosition {
[self.button mas_remakeConstraints:^(MASConstraintMaker *make) {
make.size.equalTo(self.buttonSize);
if (topLeft) {
make.top.and.left.offset(10);
} else {
make.bottom.and.right.offset(-10);
}
}];
}
五十五、iOS中的round/roundf/ceil/ceilf/floor/floorf
round:如果參數(shù)是小數(shù)篮幢,則求本身的四舍五入大刊。
ceil:如果參數(shù)是小數(shù),則求最小的整數(shù)但不小于本身(向上取三椿,ceil的英文意思有天花板的意思)
floor:如果參數(shù)是小數(shù)缺菌,則求最大的整數(shù)但不大于本身(向下取葫辐,floor的英文意思有地板的意思)
Example:如果值是3.4的話,則
3.4 – round 3.000000
– ceil 4.000000
– floor 3.00000
五十六伴郁、中文輸入法的鍵盤上有聯(lián)想耿战、推薦的功能,所以可能導致文本內(nèi)容長度上有些不符合預期蛾绎,導致越界
***Terminating app due to uncaught exception ‘NSRangeException’, reason: ‘NSMutableRLEArray replaceObjectsInRange:withObject:length:: Out of bounds’
處理方式如下(textView.markedTextRange == nil)
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
if (textView.text.length >= self.textLengthLimit && text.length > range.length) {
return NO;
}
return YES;
}
- (void)textViewDidChange:(UITextView *)textView
{
self.placeholder.hidden = (self.textView.text.length > 0);
if (textView.markedTextRange == nil && self.textLengthLimit > 0 && self.text.length > self.textLengthLimit) {
textView.text = [textView.text substringToIndex:self.textLengthLimit];
}
}
五十七昆箕、關(guān)于導航欄透明度的設置及頂部布局起點位置設置
屬性:translucent
關(guān)閉
self.navigationController.navigationBar.translucent = NO;
開啟
self.navigationController.navigationBar.translucent = YES;
屬性:automaticallyAdjustsScrollViewInsets
當 automaticallyAdjustsScrollViewInsets 為 NO 時鸦列,tableview 是從屏幕的最上邊開始租冠,也就是被 導航欄 & 狀態(tài)欄覆蓋
當 automaticallyAdjustsScrollViewInsets 為 YES 時,也是默認行為
五十八薯嗤、UIScrollView偏移64問題
在一個VC里如果第一個控件是UIScrollView顽爹,注意是第一個控件,就是首先addsubview在VC.view上骆姐。接著加到scrollView上的View就會在Y點上發(fā)生64的偏移(也就是navigationBar的高度44+電池條的高度20)镜粤。
這個在iOS7以后才會出現(xiàn)。
解決辦法:
self.automaticallyAdjustsScrollViewInsets = false; self是你當前那個VC玻褪。
如果這個scrollView不是第一個加到self.view上的肉渴。也不會發(fā)生64的偏移。
五十九带射、UIWebView在IOS9下底部出現(xiàn)黑邊解決方式
UIWebView底部的黑條很難看(在IOS8下不會同规,在IOS9會出現(xiàn)),特別是在底部還有透明控件的時候窟社,隱藏的做法其實很簡單券勺,只需要將opaque設為NO,背景色設為clearColor即可
六十灿里、tabBarController跳轉(zhuǎn)到另一個一級頁面
當我們用tabBarController時关炼,若已經(jīng)到其中一個TabBar的子頁,又要跳轉(zhuǎn)到某一個一級的頁面時匣吊,如果這樣寫儒拂,導致底部出現(xiàn)黑邊,引起tabbar消失的bug
[self.navigationController popToRootViewControllerAnimated:YES];
((AppDelegate *)AppDelegateInstance).tabBarController.selectedIndex = 2;
解決方法一:刪除動畫
[self.navigationController popToRootViewControllerAnimated:NO];
((AppDelegate *)AppDelegateInstance).tabBarController.selectedIndex = 2;
解決方法二:延遲執(zhí)行另一個系統(tǒng)操作
[self.navigationController popToRootViewControllerAnimated:NO];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
((AppDelegate *)AppDelegateInstance).tabBarController.selectedIndex = 2;
});
六十一色鸳、UIWebView獲取Html的標題title
titleLabel.text = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
六十二社痛、漢字轉(zhuǎn)為拼音
- (NSString *)Charactor:(NSString *)aString getFirstCharactor:(BOOL)isGetFirst
{
//轉(zhuǎn)成了可變字符串
NSMutableString *str = [NSMutableString stringWithString:aString];
//先轉(zhuǎn)換為帶聲調(diào)的拼音
CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
//再轉(zhuǎn)換為不帶聲調(diào)的拼音
CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO);
NSString *pinYin = [str capitalizedString];
//轉(zhuǎn)化為大寫拼音
if(isGetFirst)
{
//獲取并返回首字母
return [pinYin substringToIndex:1];
}
else
{
return pinYin;
}
}
六十三、屬性名以new開頭解決方式
因為new為OC關(guān)鍵詞缕碎,類似的還有alloc
@property (nonatomic,copy) NSString *new_Passwd;
像上面這樣寫法會報錯褥影,可以替換成
@property (nonatomic,copy,getter = theNewPasswd) NSString *new_Passwd;
六十四、去除編譯器警告
a:方法棄用告警
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
//會報警告的方法咏雌,比如SEL
[TestFlight setDeviceIdentifier:[[UIDevice currentDevice] uniqueIdentifier]];
#pragma clang diagnostic pop
b:未使用變量
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-variable"
int a;
#pragma clang diagnostic pop
六十五凡怎、self.navigationController.viewControllers修改
主要解決那些亂七八糟的跳轉(zhuǎn)邏輯校焦,不按順序來的問題;
var controllerArr = self.navigationController?.viewControllers//獲取Controller數(shù)組
controllerArr?.removeAll()//移除controllerArr中保存的歷史路徑
//重新添加新的路徑
controllerArr?.append(self.navigationController?.viewControllers[0])
controllerArr?.append(C)
controllerArr?.append(B)
//這時歷史路徑為(root -> c -> b)
//將組建好的新的跳轉(zhuǎn)路徑 set進self.navigationController里
self.navigationController?.setViewControllers(controllerArr!, animated: true)
//直接寫入统倒,完成跳轉(zhuǎn)B頁面的同時修改了之前的跳轉(zhuǎn)路徑