資料
- iOS 6
- iOS 7
- iOS 8
- iOS 9
- iOS 10
面試
Tips
-
Swift打印內(nèi)存地址
println(" str value \(str) has address: \(unsafeAddressOf(str))")
-
Obj-C屏蔽警告
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
...
#pragma clang diagnostic pop
-
打印代碼文件中函數(shù)的調(diào)用過程
clang -rewrite-objc xxx.m
-
UIWebView獲取Html標(biāo)題
-(void)webViewDidFinishLoad:(UIWebView *)webView {
titleLabel.text = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
}
-
Category添加屬性字段
@interface UIImage (category)
// 在UIImage中新建一個(gè)tag屬性
@property (nonatomic, copy) NSString *tag;
@end
static const void *tagKey = &tagKey;
@implementation UIImage (category)
-(NSString *)tag {
return objc_getAssociatedObject(self, tagKey);
}
-(void)setTag:(NSString *)tag {
objc_setAssociatedObject(self, tagKey, tag, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
@end
-
隱藏狀態(tài)欄
override func prefersStatusBarHidden() -> Bool { return true }
-
Runloop實(shí)現(xiàn)Alert同步彈窗
-(NSInteger)doModal {
[self showAlert];
_bModel = YES;
while (_bModel) {
[[NSRunLoop mainRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
return _selectBtnIndex;
}
-(void)showAlert {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:@"okookoko" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"ok", nil];
[alertView show];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
_selectBtnIndex = buttonIndex;
_bModel = NO;
}
-
UITableView的Group樣式下頂部空白處理
//分組列表頭部空白處理
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.1)];
self.tableView.tableHeaderView = view;
-
禁止鎖屏
默認(rèn)情況下痕惋,當(dāng)設(shè)備一段時(shí)間沒有觸控動(dòng)作時(shí)分瘦,iOS會(huì)鎖住屏幕。但有一些應(yīng)用是不需要鎖屏的,比如視頻播放器逼裆。
[UIApplication sharedApplication].idleTimerDisabled = YES;
-
模態(tài)推出透明界面
UIViewController *vc = [[UIViewController alloc] init];
UINavigationController *na = [[UINavigationController alloc] initWithRootViewController:vc];
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
{
na.modalPresentationStyle = UIModalPresentationOverCurrentContext;
} else {
self.modalPresentationStyle=UIModalPresentationCurrentContext;
}
[self presentViewController:na animated:YES completion:nil];
-
Xcode調(diào)試不顯示內(nèi)存占用
editSCheme 里面有個(gè)選項(xiàng)叫叫做enable zoombie Objects 取消選中
-
顯示隱藏文件
//顯示
defaults write com.apple.finder AppleShowAllFiles -bool true
killall Finder
//隱藏
defaults write com.apple.finder AppleShowAllFiles -bool false
killall Finder
-
iOS跳轉(zhuǎn)到App Store下載應(yīng)用評分
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=APPID"]];
-
手動(dòng)更改iOS狀態(tài)欄的顏色
-(void)setStatusBarBackgroundColor:(UIColor *)color
{
UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
if ([statusBar respondsToSelector:@selector(setBackgroundColor:)])
{
statusBar.backgroundColor = color;
}
}
-
獲取實(shí)際使用的LaunchImage圖片
-(NSString *)getLaunchImageName
{
CGSize viewSize = self.window.bounds.size;
// 豎屏
NSString *viewOrientation = @"Portrait";
NSString *launchImageName = nil;
NSArray* imagesDict = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"UILaunchImages"];
for (NSDictionary* dict in imagesDict)
{
CGSize imageSize = CGSizeFromString(dict[@"UILaunchImageSize"]);
if (CGSizeEqualToSize(imageSize, viewSize) && [viewOrientation isEqualToString:dict[@"UILaunchImageOrientation"]])
{
launchImageName = dict[@"UILaunchImageName"];
}
}
return launchImageName;
}
-
在當(dāng)前屏幕獲取第一響應(yīng)
UIWindow * keyWindow = [[UIApplication sharedApplication] keyWindow];
UIView * firstResponder = [keyWindow performSelector:@selector(firstResponder)];
-
判斷對象是否遵循了某協(xié)議
if ([self.selectedController conformsToProtocol:@protocol(RefreshPtotocol)])
{
[self.selectedController performSelector:@selector(onTriggerRefresh)];
}
-
判斷view是不是指定視圖的子視圖
BOOL isView = [textView isDescendantOfView:self.view];
-
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"];
-
關(guān)于NSDateFormatter的格式
G: 公元時(shí)代递胧,例如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: 時(shí)惨恭,24小時(shí)制,0-23
K:時(shí)耙旦,12小時(shí)制脱羡,0-11
m: 分,1-2位
mm: 分免都,2位
s: 秒锉罐,1-2位
ss: 秒,2位
S: 毫秒
-
獲取一個(gè)類的所有子類
+(NSArray *) allSubclasses
{
Class myClass = [self class];
NSMutableArray *mySubclasses = [NSMutableArray array];
unsigned int numOfClasses;
Class *classes = objc_copyClassList(&numOfClasses;);
for (unsigned int ci = 0; ci < numOfClasses; ci++)
{
Class superClass = classes[ci];
do{
superClass = class_getSuperclass(superClass);
} while (superClass && superClass != myClass);
if (superClass)
{
[mySubclasses addObject: classes[ci]];
}
}
free(classes);
return mySubclasses;
}
-
監(jiān)測設(shè)備是否設(shè)置了代理绕娘,需要CFNetwork.framework
NSDictionary *proxySettings = (__bridge NSDictionary *)(CFNetworkCopySystemProxySettings());
NSArray *proxies = (__bridge NSArray *)(CFNetworkCopyProxiesForURL((__bridge CFURLRef _Nonnull)([NSURL URLWithString:@"http://www.baidu.com"]), (__bridge CFDictionaryRef _Nonnull)(proxySettings)));
NSLog(@"\n%@",proxies);
NSDictionary *settings = proxies[0];
NSLog(@"%@",[settings objectForKey:(NSString *)kCFProxyHostNameKey]);
NSLog(@"%@",[settings objectForKey:(NSString *)kCFProxyPortNumberKey]);
NSLog(@"%@",[settings objectForKey:(NSString *)kCFProxyTypeKey]);
if ([[settings objectForKey:(NSString *)kCFProxyTypeKey] isEqualToString:@"kCFProxyTypeNone"])
{
NSLog(@"沒代理");
}
else
{
NSLog(@"設(shè)置了代理");
}
-
取消UICollectionView的隱式動(dòng)畫
UICollectionView在reloadItems的時(shí)候脓规,默認(rèn)會(huì)附加一個(gè)隱式的fade動(dòng)畫,有時(shí)候很討厭险领,尤其是當(dāng)你的cell是復(fù)合cell的情況下(比如cell使用到了UIStackView)侨舆。
下面幾種方法都可以幫你去除這些動(dòng)畫
//方法一
[UIView performWithoutAnimation:^{
[collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]]];
}];
//方法二
[UIView animateWithDuration:0 animations:^{
[collectionView performBatchUpdates:^{
[collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]]];
} completion:nil];
}];
//方法三
[UIView setAnimationsEnabled:NO];
[self.trackPanel performBatchUpdates:^{
[collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]]];
} completion:^(BOOL finished) {
[UIView setAnimationsEnabled:YES];
}];
-
讓Xcode的控制臺支持LLDB類型的打印
打開終端輸入三條命令:
touch ~/.lldbinit
echo display @import UIKit >> ~/.lldbinit
echo target stop-hook add -o \"target stop-hook disable\" >> ~/.lldbinit
- CocoaPods pod install/pod update更新慢的問題
pod install --verbose --no-repo-update
pod update --verbose --no-repo-update
如果不加后面的參數(shù),默認(rèn)會(huì)升級CocoaPods的spec倉庫绢陌,加一個(gè)參數(shù)可以省略這一步挨下,然后速度就會(huì)提升不少
-
GCD timer定時(shí)器
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
dispatch_source_set_timer(timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒執(zhí)行
dispatch_source_set_event_handler(timer, ^{
//@"倒計(jì)時(shí)結(jié)束,關(guān)閉"
dispatch_source_cancel(timer);
dispatch_async(dispatch_get_main_queue(), ^{
});
});
dispatch_resume(timer);
- 禁用UIWebView的默認(rèn)交互行為
public func webViewDidFinishLoad(webView: UIWebView) {
if disableUserSelect { // 禁用用戶選擇
webView.stringByEvaluatingJavaScriptFromString("document.documentElement.style.webkitUserSelect='none';")
}
if disableLongTouch { // 禁用長按彈出框
webView.stringByEvaluatingJavaScriptFromString("document.documentElement.style.webkitTouchCallout='none';")
}
}
- UIButton 移除所有事件
button.removeTarget(nil, action: nil, forControlEvents: .AllEvents)
- 在模擬器中添加視頻
//Add a video in Simulator
if let a = NSBundle.mainBundle().pathForResource("test", ofType: "mov", inDirectory: nil) {
UISaveVideoAtPathToSavedPhotosAlbum(a, self, nil, nil)
}
- 液晶時(shí)鐘字體
label.font=[UIFont fontWithName:@"DBLCDTempBlack" size:60.0];
- UIAlertController改變按鈕文字顏色
alertC.view.tintColor = your color;
//setting the tintColor after presenting the controller works on both iOS 8 and 9
問題集錦
-
Can't add self as subview
iOS7剛發(fā)布的時(shí)候脐湾,總是出現(xiàn)這個(gè) Can't add self as subview 的崩潰臭笆,異常描述和崩潰堆棧是這樣的:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Can't add self as subview'
這是因?yàn)閷?dǎo)航欄在做動(dòng)畫的時(shí)候,執(zhí)行了一次[self addSubView:self]
為了防止這種情況秤掌,我們在UINavigationController基類中加入防御愁铺,具體做法是在push,pop方法中設(shè)置一個(gè)標(biāo)志位(animating=YES)
闻鉴,在動(dòng)畫結(jié)束之后茵乱,再重置這個(gè)標(biāo)志位,然后椒拗,用這個(gè)標(biāo)志位判斷push和pop操作是否能夠執(zhí)行似将。
@interface UIViewController (Animating)
@property (nonatomic, assign) BOOL animating;
@end
@implementation BaseNavigationController
-(void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
if (topVC.animating) {
return;
}
topVC.animating = YES;
viewController.animating = YES;
[super pushViewController:viewController animated:animated];
}
@end
@implementation BaseKitViewController
-(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
self.animating = NO;
}
-(void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
self.animating = NO;
}
@end
-
TestFlight上傳不成功提示ITSAppUsesNonExemptEncryption
info.plist添加下面鍵值對
<key>ITSAppUsesNonExemptEncryption</key><false/>
-
Xcode8 手動(dòng)創(chuàng)建橋接文件Bridge-Header
-
Xib顏色設(shè)置有色差