iOS Objective开发基础知识点总结(持续更新...)

1、iOS9之后APP必须启用ATS,在info.plist添加

<key>NSAppTransportSecurity</key>
<dict>
	<key>NSAllowsArbitraryLoads</key>
	<true/>
</dict>

2、在开发过程中经常会使用一些国外大牛写的组件,哪怕系统语言是中文,但是显示依旧是英文,这种情况下,我们需要修改info.plist

<key>CFBundleDevelopmentRegion</key>
<string>china</string>

3、设置启动页面展示时间,在APPDelegate中添加

[NSThread sleepForTimeInterval:0.5];

4、解决多个控件同时响应事件的问题,在APPDelegate中添加

[[UIView appearance] setExclusiveTouch:YES];

5、设置沉浸式的样式

self.extendedLayoutIncludesOpaqueBars = YES;
if (@available(iOS 11.0, *)) {
	_webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
} else {
	self.automaticallyAdjustsScrollViewInsets = NO;
}

6、打开其他应用

// 所有的打开方式
if ([[UIApplication sharedApplication] canOpenURL:URL] == YES) {
	if (@available(iOS 10.0, *)) {
		[[UIApplication sharedApplication] openURL:URL options:@{} completionHandler:nil];
	} else {
		[[UIApplication sharedApplication] openURL:URL];
	}
} else {
	// 打开失败
}
// 打开浏览器
NSURL *URL = [NSURL URLWithString:@"http://www.baidu.com"];
// 拨打电话
NSURL *URL = [NSURL URLWithString:@"tel:%13888888888"];
// 跳转APPStore
NSString *APPID = @""; // 10位数字
NSString *URL = [@"itms-apps://itunes.apple.com/app/id" stringByAppendingString:APPID];
// 跳转APPStore评价
NSString *URL = [@"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id==" stringByAppendingString:APPID];
// 打开其他非系统应用需要添加系统白名单,在Info.plist中添加字段:LSApplicationQueriesSchemes,类型为Array,然后在Array中添加要打开的应用名
// 常用 APP 的 Url Scheme 前缀:QQ mqq://、微信 weixin://、支付宝 alipay://等

7、导航栏常用设置

// push跳转时隐藏底部Bar
self.hidesBottomBarWhenPushed = NO;
// 半透明开关
self.navigationBar.translucent = NO;
self.toolbar.translucent = NO;
// 去掉导航栏黑线
[self.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
[self.navigationBar setShadowImage:[[UIImage alloc] init]];
// 主色调和背景颜色
self.navigationBar.tintColor = [UIColor blackColor];
self.navigationBar.barTintColor = [UIColor whiteColor];
// 标题字号和颜色
self.navigationBar.titleTextAttributes = @{NSFontAttributeName : [UIFont systemFontOfSize:18], NSForegroundColorAttributeName : [UIColor blackColor]};
// 定制返回按钮图片,这两个要一起用,为啥这么用,苹果言语不详
self.navigationBar.backIndicatorImage = [UIImage imageNamed:@"Default_left"];
self.navigationBar.backIndicatorTransitionMaskImage = [UIImage imageNamed:@"Default_left"];
// 设置返回按钮只显示图片,不显示标题
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
	[super pushViewController:viewController animated:animated];
	
	viewController.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(popViewControllerAnimated:)];
}

8、

在iOS中的指令集有:armv7、armv7s、arm64、i386、x86_64,其中 armv7、armv7s、arm64 是ARM处理器的指令集,i386、x86_64 是Mac处理器的指令集。
指令集支持的设备如下:
arm64:5s之后的设备
armv7s:5, 5c
arm7:4, 4s
i386:模拟器32位
x86_64:模拟器64位

9、事件

#pragma mark - 触摸事件
// 触摸开始时执行
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
}
// 触摸移动时候执行
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
}
// 触摸意外取消时执行
- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
}
// 触摸结束时执行
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
}
#pragma mark - 运动事件
// 运动开始时执行
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
}
// 运动被意外取消时执行
- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event {
}
// 运动结束时执行
- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
}
#pragma mark - 远程控制事件
// 接收到远程控制事件时执行
- (void)remoteControlReceivedWithEvent:(UIEvent *)event {
}

10、获取当前屏幕显示的window、获取当前屏幕显示的viewcontroller

// 获取当前屏幕显示的window
- (UIWindow *)getCurrentWindow {
    
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal) {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for (UIWindow *tmpWin in windows) {
            if (tmpWin.windowLevel == UIWindowLevelNormal) {
                window = tmpWin;
                break;
            }
        }
    }
    
    return window;
}
// 获取当前屏幕显示的viewcontroller
- (UIViewController *)getCurrentVC {
    
    UIViewController *result = nil;
    UIWindow *window = [self getCurrentWindow];
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    result = [nextResponder isKindOfClass:[UIViewController class]] ? nextResponder : window.rootViewController;
    
    return result;
}

11、获取并处理字体列表

self.fontList = [NSMutableDictionary dictionary];
self.keys = [NSMutableArray array];

NSArray *familyNames = [UIFont familyNames];
for (NSString *fontName in familyNames) {
	char ch = [fontName characterAtIndex:0];
	NSString *chString = [NSString string];
	if (ch >= 65 && ch <= 90) {
		chString = [NSString stringWithFormat:@"%c", ch]; 
	} else if (ch >= 90 && ch <= 122) {
		ch = ch - 32;
		chString = [NSString stringWithFormat:@"%c", ch];
	} else {
		chString = @"#";
	}

	if ([self.keys containsObject:chString] == NO) {
		[self.keys addObject:chString];
		NSMutableArray *values = [NSMutableArray arrayWithObject:fontName];
		[self.fontList setObject:values forKey:chString];
	} else {
		NSMutableArray *values = [NSMutableArray arrayWithArray:self.fontList[chString]];
		[values addObject:fontName];
		[self.fontList setObject:values forKey:chString];
	}
}
// 排序,升序
[self.keys sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
	return [obj1 compare:obj2];
}];

12、键盘监听

// 键盘即将出现
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
// 键盘出现
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
// 键盘即将消失
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
// 键盘消失
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHide:) name:UIKeyboardDidHideNotification object:nil];
// 实现键盘监听
- (void)keyboardWillShow:(NSNotification *)notification {
}
- (void)keyboardDidShow:(NSNotification *)notification {
}
- (void)keyboardWillHide:(NSNotification *)notification {
}
- (void)keyboardDidHide:(NSNotification *)notification {
}

13、计算并清理缓存

// 计算目录大小
- (NSString *)getCacheSizeWithFilePath:(NSString *)path {
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
        NSArray *subpaths = [[NSFileManager defaultManager] subpathsAtPath:path];
        CGFloat folderSize = 0;
        for (NSString *sub in subpaths) {
            // 1. 拼接每一个文件的全路径
            NSString *absolutePath = [path stringByAppendingPathComponent:sub];
            // 2. 是否是文件夹,默认不是
            BOOL isDirectory = NO;
            // 3. 判断文件是否存在
            BOOL isExist = [[NSFileManager defaultManager] fileExistsAtPath:absolutePath isDirectory:&isDirectory];
            // 4. 以上判断目的是忽略不需要计算的文件
            if (!isExist || isDirectory || [absolutePath containsString:@".DS"]){
                // 过滤: 1. 文件夹不存在  2. 过滤文件夹  3. 隐藏文件
                continue;
            }
            // 5. 获取每一个文件的大小
            long long size = [[NSFileManager defaultManager] attributesOfItemAtPath:absolutePath error:nil].fileSize;
            // 6. 计算总大小
            folderSize += size;
        }
        if (folderSize > 1024 * 1024) {
            return [NSString stringWithFormat:@"%.2fM", folderSize / 1024 / 1024];
        } else if (folderSize > 1024) {
            return [NSString stringWithFormat:@"%.2fKB", folderSize / 1024];
        } else {
            return [NSString stringWithFormat:@"%.2fB", folderSize];
        }
    }
    
    return @"0";
}
// 清理缓存
- (BOOL)clearCacheWithFilePath:(NSString *)path {
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
        NSArray *subpaths = [[NSFileManager defaultManager] subpathsAtPath:path];
        NSError *error = nil;
        for (NSString *sub in subpaths) {
            NSString *absolutePath = [path stringByAppendingPathComponent:sub];
            [[NSFileManager defaultManager] removeItemAtPath:absolutePath error:&error];
            return error ? NO : YES;
        }
    }
    
    return YES;
}

14、原生分享

- (void)shareWithText:(NSString *)text
            imageName:(NSString *)imageName
            urlString:(NSString *)urlString {
    
    NSArray *items = @[text, [UIImage imageNamed:imageName], [NSURL URLWithString:urlString]];
    UIActivityViewController *vc = [[UIActivityViewController alloc] initWithActivityItems:items applicationActivities:nil];
    // 默认分享到的位置
    // UIActivityTypePostToFacebook
    // UIActivityTypePostToTwitter
    // UIActivityTypePostToWeibo
    // UIActivityTypeMessage
    // UIActivityTypeMail
    // UIActivityTypePrint
    // UIActivityTypeCopyToPasteboard
    // UIActivityTypeAssignToContact
    // UIActivityTypeSaveToCameraRoll
    // UIActivityTypeAddToReadingList
    // UIActivityTypePostToFlickr
    // UIActivityTypePostToVimeo
    // UIActivityTypePostToTencentWeibo
    // UIActivityTypeAirDrop
    // UIActivityTypeOpenInIBooks
    // UIActivityTypeMarkupAsPDF
    // 拒绝分享到的位置,根据需要从上面筛选
    vc.excludedActivityTypes = @[UIActivityTypeAirDrop, UIActivityTypeMail];
    [self presentViewController:vc animated:YES completion:nil];
    vc.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
        if (completed) {
            NSLog(@"分享成功!");
        }
    };
}

15、清理图片缓存

[[SDImageCache sharedImageCache] clearMemory];

猜你喜欢

转载自blog.csdn.net/qq_16804091/article/details/85128083