目录
1.App权限
2.跳转
2.1 跳转到手机设置界面
2.2 打电话/发短信/email/http/AppStore
2.3 跳转同一开发者账号下的其他App
2.4 跳转其他常用应用的URL
2.5 短信中链接跳转App(指定页面)
2.6 其他常用
3.XCode快捷键
4.快捷代码片段
5.自定义UINavBarController
6.自定义UITabBarController
1. App权限
注意:
没加相关权限,程序可能直接崩溃!
<!-- 网络https -->
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
<!-- 相机 -->
<key>NSCameraUsageDescription</key>
<string>App需要您的同意,才能访问相机</string>
<!-- 相册 -->
<key>NSPhotoLibraryUsageDescription</key>
<string>App需要您的同意,才能访问相册</string>
<!-- 麦克风 -->
<key>NSMicrophoneUsageDescription</key>
<string>App需要您的同意,才能访问麦克风</string>
<!-- 媒体资料库 -->
<key>NSAppleMusicUsageDescription</key>
<string>App需要您的同意,才能访问媒体资料库</string>
<!-- 蓝牙 -->
<key>NSBluetoothPeripheralUsageDescription</key>
<string>App需要您的同意,才能访问蓝牙</string>
<!-- 语音识别(语音转文字) -->
<key>Privacy - Speech Recognition Usage Description </key>
<string>App需要使用语音识别</string>
<!-- 通讯录 -->
<key>Privacy - Contacts Usage Description</key>
<string>App需要访问您的通讯录</string>
<!-- 位置 -->
<key>NSLocationUsageDescription</key>
<string>App需要您的同意,才能访问位置</string>
<!-- 在使用期间访问位置 -->
<key>NSLocationWhenInUseUsageDescription</key>
<string>App需要您的同意,才能在使用期间访问位置</string>
<!-- 始终访问位置 -->
<key>NSLocationAlwaysUsageDescription</key>
<string>App需要您的同意,才能始终访问位置</string>
<!-- 日历 -->
<key>NSCalendarsUsageDescription</key>
<string>App需要您的同意,才能访问日历</string>
<!-- 提醒事项 -->
<key>NSRemindersUsageDescription</key>
<string>App需要您的同意,才能访问提醒事项</string>
<!-- 运动与健身 -->
<key>NSMotionUsageDescription</key>
<string>App需要您的同意,才能访问运动与健身</string>
<!-- 健康更新 -->
<key>NSHealthUpdateUsageDescription</key>
<string>App需要您的同意,才能访问健康更新 </string>
<!-- 健康分享 -->
<key>NSHealthShareUsageDescription</key>
<string>App需要您的同意,才能访问健康分享</string>
<!-- 提醒 -->
<key>Privacy - Reminders Usage Description</key>
<string>App需要使用您的提醒功能</string>
<!-- Siri -->
<key>Privacy - Siri Usage Description</key>
<string>App需要使用您的Siri功能</string>
<!-- 电视供应商 -->
<key>Privacy - TV Provider Usage Description</key>
<string>App需要使用您的电视供应商功能</string>
<!-- 视频用户账号 -->
<key>Privacy - Video Subscriber Account Usage Description</key>
<string>App需要使用您的视频用户账号</string>
2. 跳转
2.1 跳转到手机设置界面
注意:
iOS10 后改为App-Prefs:(有个别失效)
// 跳转到设置---蜂窝网络
[[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"App-Prefs:root=MOBILE_DATA_SETTINGS_ID"]];
系统设置---本应用的设置(直接写 定位可以写这个)
UIApplicationOpenSettingsURLString
无线局域网WiFi
App-Prefs:root=WIFI
蜂窝移动网络
App-Prefs:root=MOBILE_DATA_SETTINGS_ID
个人热点
App-Prefs:root=INTERNET_TETHERING
通知
App-Prefs:root=NOTIFICATIONS_ID
蓝牙
App-Prefs:root=Bluetooth
音乐
App-Prefs:root=MUSIC
音乐-均衡器
App-Prefs:root=MUSIC&path=com.apple.Music:EQ
声音
App-Prefs:root=Sounds
照片与相机
App-Prefs:root=Photos
FACEBOOK
App-Prefs:root=FACEBOOK
FaceTime
App-Prefs:root=FACETIME
TWITTER
App-Prefs:root=TWITTER
iTunes Store
App-Prefs:root=STORE
iCloud
App-Prefs:root=CASTLE
iCloud下存储空间
App-Prefs:root=CASTLE&path=STORAGE_AND_BACKUP
VPN
App-Prefs:root=General&path=VPN
电话
App-Prefs:root=Phone
电话铃声
App-Prefs:root=Sounds&path=Ringtone
通讯录
App-Prefs:root=ACCOUNT_SETTINGS
备忘录
App-Prefs:root=NOTES
运营商
App-Prefs:root=Carrier
Siri
App-Prefs:root=SIRI
隐私
App-Prefs:root=Privacy
Safari
App-Prefs:root=SAFARI
墙纸
App-Prefs:root=Wallpaper
描述文件
App-Prefs:root=General&path=ManagedConfigurationList
系统更新
App-Prefs:root=General&path=SOFTWARE_UPDATE_LINK
通用
App-Prefs:root=General
通用---语言与地区
App-Prefs:root=General&path=INTERNATIONAL
通用---日期与时间
App-Prefs:root=General&path=DATE_AND_TIME
通用---键盘
App-Prefs:root=General&path=Keyboard
通用---辅助功能
App-Prefs:root=General&path=ACCESSIBILITY
通用---关于本机
App-Prefs:root=General&path=About
通用---还原
App-Prefs:root=General&path=Reset
2.2 打电话/发短信/email/http/AppStore
注意:
iOS10.2之后一定会弹出 系统电话框
// 打电话/发短信/email/http/AppStore
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://13088888888"]]; // 也可+86
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"sms://13051178888"]];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"mail://hello@hello.com"]];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.baidu.com”]];
[[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"https://itunes.apple.com/us/app/****/id12**953892?mt=8"]];
// 是否可以打开
BOOL isCanOpen=[[UIApplication sharedApplication]canOpenURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",KF_PHONE]]];
// 解决【打电话延迟】添加options参数——@{}
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:PhoneStr] options:@{} completionHandler:^(BOOL success) {
NSLog(@"phone success");
}];
2.3 跳转同一开发者账号下的其他App
App1
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"xxx://www.com.cx?x=1"]];
App2
项目 | Info | URL Types 添加Scheme :xxx
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
//
NSString *schemeStr=url.scheme;
if([schemeStr caseInsensitiveCompare:@"xxx"]==NSOrderedSame){ // 不分大小写 比较相同
}
}
2.4 跳转其他常用应用的URL
iBook书籍
itms-books://
Map原生地图
maps://
Facetime视频
facetime://
QQ
mqq://
微信
weixin://
淘宝
taobao://
点评
dianping:// dianping://search
微博
sinaweibo://
名片全能王
camcard://
weico微博
weico://
支付宝
alipay://
豆瓣fm
doubanradio://
微盘
sinavdisk://
网易公开课
ntesopen://
美团
i**://
京东
openapp.jdmoble://
人人
renren://
我查查
wcc://
1号店
wccbyihaodian://
有道词典
yddictproapp://
知乎
zhihu://
优酷
youku://
2.5 短信中链接跳转App(指定页面)3方式
方式一:URL Scheme(装则跳,没装则不跳)
1. 添加URL Scheme
2. 短信中点击ddd://sssssbbbb则跳到App(没安装App则不跳)
3. 做额外处理(如:跳转到指定页面)
AppDelegate
- (BOOL)application:(UIApplication *)app
openURL:(NSURL *)url
options:(NSDictionary *)options {
// ddd://id=1234567
NSString *urlStr=url.absoluteString;
if([urlStr hasPrefix:@"ddd"]){ //
NSArray *array=[urlStr componentsSeparatedByString:@"//"];
}
return true;
}
![](https://img.haomeiwen.com/i5111884/6898b56ce57a354d.png)
方式二:通用链接(Universal Links)
可用来从微信跳转到我们的app
1.开发者中心开启Associated Domains
2.项目 | Capabilities | Associated Domains 开启,并添加applinks:hello(必须以applinks:开头)
3.创建json文件并命名apple-app-site-association(必须切无后缀,并上传到域名根目录)
{
"applinks": {
"apps": [],
"details": [
{
"appID": "teamId.bundleId”, 需改
"paths": [ "/wwdc/news/", "/videos/wwdc/2015/*"] 可处理哪些路径
}
]
}
}
验证json文件的网址:https://search.developer.apple.com/appsearch-validation-tool/
4.AppDelegate
- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray * _Nullable))restorationHandler{
//
if ([userActivity.activityType isEqualToString:NSUserActivityTypeBrowsingWeb]){
NSURL *url = userActivity.webpageURL;
if ([url.absoluteString isEqualToString:@""]){
}else{
[[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
}];
}
}
return YES;
}
方式三:跳到网页
1.填写URL Scheme
2.网页区分iOS和Android系统
跳转到URLScheme(装则跳App,没装则让它去跳下载页)
3.短信中的地址为上述网页
2.6 其他常用
截屏View
UIView *snapshot = [view snapshotViewAfterScreenUpdates:YES];
复制到剪切板
let pasteboard = UIPasteboard.generalPasteboard()
pasteboard.string = "复制到剪切板的文字"
震动
AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))
统计代码行数
type
find . "(" -name "*.m" -or -name "*.mm" -or -name "*.cpp" -or -name "*.h" -or -name "*.rss" ")" -print | xargs wc -l
1. XCode快捷键
常用:
cmd+F 搜索/替换
cmd+空格 输入z 回车 打开终端
cmd+option+左箭头/右箭头 缩放代码块
cmd+control+左箭头/右箭头 按浏览记录切换
cmd+control+上箭头/下箭头 切换.h/.m
选中代码行cmd+[ ] 左移右移代码块
cmd+A ctr+I 格式化代码缩进
快速查找—搜索
cmd+F : 搜索本文件内容
cmd+3 : Xcode左上搜索🔍(文件内容). Xcode左下🔍中搜索(文件名)
cmd+shift+O : 搜索文件/方法名(快速打开)
cmd+空格(Spotlight) : 搜索 应用/文件(快速打开)
快速查找—方法列表
ctl+6 : 查看方法列表
ctl+2 : 查看历史浏览
ctl+5 : 查看组内文件
XCode工具
cmd+option+0 :隐藏/显示 右边栏(0—n)
cmd+0 : 隐藏左边栏 (0—n)
cmd+1 : 展开左边栏
cmd+shift+Y : 展开隐藏调试栏
cmd+control+up :切换.h和.m
cmd+control+left :切换历史文件
option+文件 :在辅助界面打开该文件(双圈)
option+view.swift :可在双界面下选择要连线的view
cmd+shift+j. :当前编辑文件置蓝
文本编辑
cmd+[ 或 ] : 选中代码左移 或 右移
shift+左右箭头 : 逐字向左右选中
cmd+左右箭头 : 移动到最左右
cmd+上下箭头 : 移动到最上下
cmd+option+<— : 语句块缩小。(放大同理)。 +shift(全部缩小)
esc : 代码提示
cmd+delete : 删除本行
cmd+C、V、X、A、S、/ 、Z : 复制、粘贴、剪切、全选、保存、注释、撤销
control+I : 格式化代码
cmd+shift+1 : 打开Xcode欢迎页面(新建项目)
cmd+N、W、R、.、\ : 新建文件、关闭Xcode、运行程序、停止程序、当前行打断点.
control+空格 : 切换输入法
cmd+shif+G : 前往文件夹 (寻找.dliyb cmd+shift+G:/usr/lib/ )
cmd+shift+0 : 打开类帮助文档
双圈模式下,ctl+1 : callers. : 查看方法谁调用了
特殊符号及表情
⌃⌘spacing
MAC快捷键
应用设置: ⌘,
隐藏应用: ⌘H
退出应用: ⌘Q
键盘
⌘: Command键
⇧: shift键
⌃: control键
⌥: option键
↩︎: return键
⇞: 小键盘page up键
⇟: 小键盘page down键
↖︎: 小键盘home键
↘︎: 小键盘end键
⌫: delete键
⌦: 小键盘delete键
⎋: esc键
2.快捷代码片段
存储的位置:~/Library/Developer/Xcode/UserData/CodeSnippets
选中代码-选择拖入-双击Edit-填写shortcut)
1.strong:
@property (nonatomic,strong) <#Class#> *<#object#>;
2.weak:
@property (nonatomic,weak) <#Class#> *<#object#>;
3.copy:
@property (nonatomic,copy) NSString *<#string#>;
4.assign:
@property (nonatomic,assign) <#Class#> <#property#>;
5.delegate:
@property (nonatomic,weak) id<<#protocol#>> <#delegate#>;
6.block:
@property (nonatomic,copy) <#Block#> <#block#>;
7.mark:
#pragma mark <#mark#>
8.cell
/**获取tableViewCell
*/
+(instancetype)CellWithTableView:(UITableView *)tableView{
static NSString *iden=<#iden#>;
<#Class#> *cell=[tableView dequeueReusableCellWithIdentifier:iden];
if(cell){ //
cell=[[<#Class#> alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:iden];
}
return cell;
}
9.mainGCD
dispatch_async(dispatch_get_main_queue(), ^{
<#code#>
});
9.afterGCD
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(<#delayInSeconds#> * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
<#code to be executed after a specified delay#>
});
9.onceGCD
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
<#code to be executed once#>
});
3.自定义UINavBarController
YTNavBarController.h
#import <UIKit/UIKit.h>
@interface YTNavBarController : UINavigationController
@end
YTNavBarController.m
#import "YTNavBarController.h"
#import "YTTabBarController.h"
@interface YTNavBarController ()
@end
@implementation YTNavBarController
/**
* 第一次使用这个类的时候会调用(1个类只会调用1次)
*/
+ (void)initialize{
// 设置导航栏主题
[self setupNavBarTheme];
}
/**
* 设置导航栏主题
*/
+ (void)setupNavBarTheme{
// 获取导航栏单例
UINavigationBar *navBar = [UINavigationBar appearance];
// 设置导航栏 文本颜色
[navBar setTintColor:[UIColor whiteColor]];
// 设置导航栏 背景色
navBar.barTintColor=YTMainColor;
// 设置导航栏 是否半透明(默认:true,从屏幕左上角为坐标原点)(即使图片无透明也使其透明,设置barTintColor则不再透明
navBar.translucent=false;
// 隐藏导航栏 返回按钮文字(移到屏幕外)
[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)
forBarMetrics:UIBarMetricsDefault];
// 设置导航栏 标题
[navBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:YTFONT_PF(18)}];
// 设置导航栏 返回按钮
[navBar setBackIndicatorImage:[UIImage imageNamed:@"backNavT"]];
[navBar setBackIndicatorTransitionMaskImage:[UIImage imageNamed:@"backNavT"]];
/**
// 设置导航栏 风格
[navBar setBarStyle:UIBarStyleDefault]; // 默认(白色背景、黑色文字、状态栏文字黑色) ,UIBarStyleBlack(黑色背景、白色文字,状态栏文字白色) 发生冲突时优先级低
// 设置导航栏 背景图片
[navBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
navigationItem (在push前不要设,此时还不在push栈中,所以无效)
// 设置导航栏 标题文本
self.navigationItem.title=@"";
// 设置导航栏 标题视图
self.navigationItem.titleView=[UIView new];
// 设置导航栏 返回项
self.navigationItem.backBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:[UIView new]];
// 设置导航栏 返回项标题属性
[self.navigationItem.backBarButtonItem setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:18]} forState:UIControlStateNormal];
// 设置导航栏 右侧项
self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:[UIView new]];
// 去除导航栏下方的黑线
[[UINavigationBar appearance] setShadowImage:[UIImage new]];
[[UINavigationBar appearance] setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
*/
}
- (void)viewDidLoad{
[super viewDidLoad];
// 侧滑手势dele:self <UIGestureRecognizerDelegate>
// self.interactivePopGestureRecognizer.delegate = self;
}
/**
* 状态栏文字颜色 白色
*/
-(UIStatusBarStyle)preferredStatusBarStyle{
return UIStatusBarStyleLightContent;
}
/**
* 重写这个方法,当控制器跳转时自动隐藏底部导航
*/
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated{
// viewController.hidesBottomBarWhenPushed = YES; 系统TabBar
// 自定义tabBar
((YTTabBarController *)self.tabBarController).tabBarView.hidden=true;
[super pushViewController:viewController animated:animated];
}
-(UIViewController *)popViewControllerAnimated:(BOOL)animated{
if (self.viewControllers.count ==2) {
// 造成一个问题:侧滑时效果不好,侧滑中途取消时bug
((YTTabBarController *)self.tabBarController).tabBarView.hidden=false;
}
return [super popViewControllerAnimated:true];
}
-(NSArray<UIViewController *> *)popToRootViewControllerAnimated:(BOOL)animated{
// 不允许侧滑
// [self.interactivePopGestureRecognizer setEnabled:false];
((YTTabBarController *)self.tabBarController).tabBarView.hidden=false;
return [super popToRootViewControllerAnimated:animated];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
每个模块颜色不一
0.
YTNavBarController 中不设置统一背景色
1.
每个模块一个子YTNavBarController
-(void)viewDidLoad{
[super viewDidLoad];
[self.navigationBar setBarTintColor:YTRGBColor(65 ,150 ,160)];
}
导航栏切换
原始方法 在VC的viewWillAppear方法中设置相应样式
缺点:交互太突兀,侧滑问题
情境一 无导航栏和有导航切换
隐藏和重新展示navBar
viewWillAppear
[self.navigationController setNavigationBarHidden:true animated:animated];
viewWillDisappear
[self.navigationController setNavigationBarHidden:false animated:true];
情景二 不同样式导航栏切换
方法一:
隐藏导航栏 + 自定义NavigationBar(侧滑失效:重新设置侧滑dele)
[self.navigationController setNavigationBarHidden:true animated:animated];
方法二:
?
侧滑动画?
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
//
[self.transitionCoordinator animateAlongsideTransitionInView:self.view animation:^(id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) {
//
self.navigationController.navigationBar.alpha=1.0;
} completion:^(id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) {
}];
}
全屏侧滑
:UINavigationController<UIGestureRecognizerDelegate>
-(void)viewDidLoad{
//
UIGestureRecognizer *gesture=self.interactivePopGestureRecognizer;
gesture.enabled=false;
UIPanGestureRecognizer *panG=[[UIPanGestureRecognizer alloc]initWithTarget:gesture.delegate action:@selector(handleNavigationTransition:)];
[panG setDelegate:self];
[gesture.view addGestureRecognizer:panG];
}
-(BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
if(self.childViewControllers.count>1){
return true;
}
return false;
}
4.自定义UITabBarController-----系统TabBar(OC)
+(void)initialize{
// 状态栏项(统一设置)
UITabBarItem *barItem=[UITabBarItem appearance];
// 状态栏项 文字的默认/选中颜色
[barItem setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor grayColor]} forState:UIControlStateNormal];
[barItem setTitleTextAttributes:@{NSForegroundColorAttributeName:kbuttongroundColor} forState:UIControlStateSelected];
}
- (void)viewDidLoad {
[super viewDidLoad];
NSArray *contentArr=@[@[@"VC1",@"title1",@"img1",@"imgSelect1"],@[@"VC2",@"title2",@"img2",@"imgSelect2"]];
for(NSArray *arr in contentArr){
UIViewController *vc=(UIViewController *)NSClassFromString(arr[0]);
NSString *title=contentArr[1];
NSString *imgName=contentArr[2];
NSString *imgSelectName=contentArr[3];
vc.title=title;
vc.tabBarItem=[[UITabBarItem alloc]initWithTitle:title image:[[UIImage imageNamed:imgName]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] selectedImage:[[UIImage imageNamed:imgSelectName]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
[self addChildViewController:[[UINavigationController alloc]initWithRootViewController:vc]];
}
}
其他
// VCs
[self setViewControllers:@[]];
// 填充色
[self.tabBar setTintColor:kbuttongroundColor];
// 半透明
[self.tabBar setTranslucent:true];
// dele
[self.tabBar setDelegate:self];
// 是否允许选中
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController{
return true;
}
// 选中后调用
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController{}
//
-(void)tabBarController:(UITabBarController *)tabBarController willBeginCustomizingViewControllers:(NSArray<__kindof UIViewController *> *)viewControllers{}
//
- (void)tabBarController:(UITabBarController *)tabBarController willEndCustomizingViewControllers:(NSArray<__kindof UIViewController *> *)viewControllers changed:(BOOL)changed{}
//
- (void)tabBarController:(UITabBarController *)tabBarController didEndCustomizingViewControllers:(NSArray<__kindof UIViewController *> *)viewControllers changed:(BOOL)changed{}
//
- (UIInterfaceOrientationMask)tabBarControllerSupportedInterfaceOrientations:(UITabBarController *)tabBarController{}
//
- (UIInterfaceOrientation)tabBarControllerPreferredInterfaceOrientationForPresentation:(UITabBarController *)tabBarController{}
//
-(id<UIViewControllerInteractiveTransitioning>)tabBarController:(UITabBarController *)tabBarController interactionControllerForAnimationController:(id<UIViewControllerAnimatedTransitioning>)animationController{}
//
- (nullable id <UIViewControllerAnimatedTransitioning>)tabBarController:(UITabBarController *)tabBarController
animationControllerForTransitionFromViewController:(UIViewController *)fromVC
toViewController:(UIViewController *)toVC{}
*/
4.自定义UITabBarController-----系统TabBar(Swift)
class MainViewController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
// 添加子控制器
addViewController()
}
// 添加子控制器 (默认:tabbar背景色:灰色,item选中 文字图片颜色:蓝色,item未选中 文字图片颜色:灰色)
func addViewController() {
let firstC=FirstViewController()
let secondC=SecondViewController()
let thirdC=ThirdViewController()
let forthC=ForthViewController()
let myC=MyViewController()
let arr=[["食谱","食谱A","食谱B",firstC],["购喜欢","喜欢A","喜欢B",secondC],["社区","社区A","社区B",thirdC],["食课","食课A","食课B",forthC],["我的","我的A","我的B",myC]]
for i in 0..<arr.count{
self.addChildDetail(arr[i][0] as! String, imgName: arr[i][1] as! String, selectedImgName: arr[i][2] as! String, vc: arr[i][3] as! UIViewController)
}
}
func addChildDetail(title:String,imgName:String,selectedImgName:String,vc:UIViewController){
let navC=UINavigationController.init(rootViewController: vc)
vc.navigationItem.title=title
vc.tabBarItem=UITabBarItem.init(title: title, image: UIImage.init(named: imgName), selectedImage: UIImage.init(named: selectedImgName))
// 设置 标题颜色、字体
vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFontOfSize(12),NSForegroundColorAttributeName:TEXTGRAYCOLOR], forState: .Normal)
vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFontOfSize(12),NSForegroundColorAttributeName:UIColor.orangeColor()], forState: .Selected)
// 设置 图片位置
vc.tabBarItem.imageInsets=UIEdgeInsetsMake(8, 0, -8, 0) // 上下设置为 相反数,否则点击有问题
self.addChildViewController(navC)
}
}
4.自定义UITabBarController-----自定义TabBar
YTTabBarController.h
#import <UIKit/UIKit.h>
@interface YTTabBarController : UITabBarController
@property (nonatomic,strong) UIView *tabBarView;
@end
YTTabBarController.m
#import "YTTabBarController.h"
#import "YTNavBarController.h"
@interface YTTabBarController ()
@property (nonatomic,copy) NSMutableArray *dataArr;
@property (nonatomic,strong) UIButton *oldButton;
@end
@implementation YTTabBarController
//
- (void)viewDidLoad {
//
[super viewDidLoad];
[self setupData];
[self setupUI];
}
// data
-(void)setupData{
//
_dataArr=[NSMutableArray arrayWithCapacity:10];
[_dataArr addObject:@[@"首页",@"YTHomeViewController",@"homeN",@"homeS"]];
[_dataArr addObject:@[@"消息",@"YTConversationListController",@"messageN",@"messageS"]];
[_dataArr addObject:@[@"个人",@"YTMyViewController",@"myN",@"myS"]];
//
for(int i=0;i<_dataArr.count;i++){
[self addChildViewController:[[YTNavBarController alloc]initWithRootViewController:
[NSClassFromString(_dataArr[i][1]) new]]];
}
}
//
-(void)setupUI{
// 获取到系统tabbar的frame移除系统tabbar
CGRect frame=self.tabBar.frame;
frame.size=CGSizeMake(frame.size.width, 56);
frame.origin=CGPointMake(frame.origin.x, frame.origin.y-7);
[self.tabBar removeFromSuperview];
//
UIView *tabBarView=[UIView new];
_tabBarView=tabBarView;
[tabBarView setBackgroundColor:[UIColor whiteColor]];
[self.view addSubview:tabBarView];
[tabBarView setFrame:frame];
//
UIView *lineView=[UIView new];
[lineView setBackgroundColor:LINE_COLOR];
[tabBarView addSubview:lineView];
[lineView autoSetDimension:ALDimensionHeight toSize:0.6];
[lineView autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:0];
[lineView autoPinEdgeToSuperviewEdge:ALEdgeRight withInset:0];
[lineView autoPinEdgeToSuperviewEdge:ALEdgeTop withInset:0];
//
CGFloat width=KScreenWidth/_dataArr.count;
for(int i=0;i<_dataArr.count;i++){
//
UIButton *button=[UIButton new];
[button setTag:100+I];
[button addTarget:self action:@selector(handleButton:) forControlEvents:UIControlEventTouchUpInside];
[button setImage:[UIImage imageNamed:_dataArr[i][2]] forState:UIControlStateNormal];
[button setImage:[UIImage imageNamed:_dataArr[i][3]] forState:UIControlStateSelected];
[button setAdjustsImageWhenHighlighted:false];
[tabBarView addSubview:button];
[button autoPinEdgeToSuperviewEdge:ALEdgeTop withInset:0];
[button autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:0];
[button autoSetDimension:ALDimensionWidth toSize:width];
[button autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:width*I];
[button.titleLabel setFont:[UIFont fontWithName:@"苹方-简" size:12]];
[button setTitle:_dataArr[i][0] forState:UIControlStateNormal];
[button setTitleColor:YTColorFromRGB(0x27afc3) forState:UIControlStateSelected];
[button setTitleColor:YTColorFromRGB(0x7cdbe9) forState:UIControlStateNormal];
[button setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
[button setTitleEdgeInsets:UIEdgeInsetsMake(5+button.imageView.frame.size.height ,-button.imageView.frame.size.width, 0.0,0.0)];//文字距离上边框的距离增加imageView的高度,距离左边框减少imageView的宽度,距离下边框和右边框距离不变
[button setImageEdgeInsets:UIEdgeInsetsMake(-15, 0.0,0.0, -button.titleLabel.bounds.size.width)]; // 图片距离右边框距离减少图片的宽度,其它不边
if(i==0){
button.selected=true;
_oldButton=button;
}
}
}
//
-(void)handleButton:(UIButton *)button{
if(button==_oldButton){
return;
}
if(_oldButton){
_oldButton.selected=false;
}
_oldButton=button;
button.selected=true;
self.selectedIndex=button.tag-100;
}
@end
网友评论