Xcode奇淫巧技(四)——代码块Code Snippets

在iOS开发过程中,经常会用到一些相似的代码。我们能不能将这些代码保存起来,重复使用呢?回答是可以的。我们来看一下Xcode代码片段——Code Snippets。

初识代码片段

1. 新增
  • 书写如下语句
@property (nonatomic, strong) <#type#> *<#value#>;

<##> 作用是占位,## 之间可以输入提示文字。

  • 快捷键:cmd+opt+0(Xcode 10 已移至右上角)

  • 将上述代码,鼠标左键拖到下图(选中右键 create code snippet)
    这里写图片描述

  • 弹出下图所示
    这里写图片描述

Title:标题。
Summary:描述文字。
Platform:可以使用的平台(如iOS)。
Language:可以在哪些语言中使用(如 Objective-C)。
Completion Shortcut:快捷方式,以字母开头(支持少数符号,如@)。
Completion Scopes:作用范围,一般写在正确的位置拖动即可,Xcode会自行选择好。


3. 修改

对代码片段进行修改,选中代码片段,点击edit即可。


4. 删除

对代码片段进行删除,选中代码片段,按delete键即可。


常用片段

@property之类的使用了插件,也可以Code Snippets自己写,不赘述。

Title: #pragma mark 
Completion Shortcut: @mark 
Completion Scopes: Class Implementation 
  
#pragma mark <#mark#>
Title: GCD: Dispach gcdmain
Completion Shortcut: @gcdmain 
Completion Scopes: Function or Method
  
dispatch_async(dispatch_get_main_queue(), ^{
	<#code#>
});
Title: GCD: Dispach gcdglobal
Completion Shortcut: @gcdglobal 
Completion Scopes: Function or Method
  
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    <#code#>
});

dispatch_after自带

dispatch_once自带

Title: Static NSString
Completion Shortcut: @staticstring 
Completion Scopes: Top Level
  
static NSString* const <#name#> = <#value#>;
Title: Static NSInteger
Completion Shortcut: @staticint 
Completion Scopes: Top Level
  
static const NSInteger <#name#> = <#value#>;
Title: NSLog
Completion Shortcut: @log 
Completion Scopes: Function or Method
  
NSLog(@"<#Log#>");
Title: weakself
Completion Shortcut: @weakself 
Completion Scopes: Function or Method
  
__weak typeof(self) weakSelf = self;
Title: strongSelf
Completion Shortcut: @strongSelf 
Completion Scopes: Function or Method
  
__strong typeof(<#weakSelf#>) strongSelf = <#weakSelf#>;
Title: sharedInstance
Completion Shortcut: @instance 
Completion Scopes: Class Implementation
  
+ (instancetype)sharedInstance
{
    static id _sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[self alloc] init];
    });
    return _sharedInstance;
}
Title: tableinit
Completion Shortcut: @tableinit 
Completion Scopes: Function or Method
  

    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [tableView registerClass:[<#classCell#> class] forCellReuseIdentifier:<#kReuseIdentifier#>];
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.backgroundColor=[UIColor colorWithHex:<#0xFFFFFF#>];
    [<#view#> addSubview:tableView];

Title: tableDelegate
Completion Shortcut: @tableDelegate 
Completion Scopes: Class Implementation
  
#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return <#count#>;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    <#classCell#> *cell = [tableView dequeueReusableCellWithIdentifier:<#kReuseIdentifier#> forIndexPath:indexPath];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return <#rowHeight#>;
}

Title: buttoninit
Completion Shortcut: @buttoninit 
Completion Scopes: Function or Method
  

    UIButton *button = [[UIButton alloc] init];
    button.backgroundColor = [UIColor <#backgroundColor#>];
    button.titleLabel.font = [UIFont <#font#>];
    [button setTitle:<#title#> forState:UIControlStateNormal];
    [button setTitleColor:[UIColor <#titleColor#>] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [<#view#> addSubview:button];

Title: borderButton
Completion Shortcut: @borderbutton 
Completion Scopes: Function or Method
  


    UIButton *borderButton = [[UIButton alloc] init];
    borderButton.layer.borderColor = [UIColor <#color#>].CGColor;
    borderButton.layer.borderWidth = <#borderWidth#>;
    borderButton.titleLabel.font = [UIFont <#font#>];
    borderButton.clipsToBounds = YES;
    borderButton.layer.cornerRadius = <#cornerRadius#>;
    borderButton.backgroundColor = [UIColor <#backgroundColor#>];
    [borderButton setTitleColor:[UIColor <#titleColor#>] forState:UIControlStateNormal];
    [borderButton setTitle:<#title#> forState:UIControlStateNormal];
    [borderButton addTarget:self action:@selector(borderButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [<#code#> addSubview:borderButton];


Title: labelinit
Completion Shortcut: @labelinit 
Completion Scopes: Function or Method
  

    UILabel *label = [[UILabel alloc] init];
    label.font = [UIFont <#font#>];
    label.text = <#text#>
    label.textColor = [UIColor <#textColor#>];
    label.textAlignment = NSTextAlignmentCenter;
    label.backgroundColor = [UIColor clearColor];
    [<#view#> addSubview:label];

Title: attributedLabel
Completion Shortcut: @attributedLabel 
Completion Scopes: Function or Method
  


    UILabel *attributedLabel =[[UILabel alloc] init];
    attributedLabel.numberOfLines = 0;
    attributedLabel.preferredMaxLayoutWidth = <#preferredMaxLayoutWidth#>;
    attributedLabel.backgroundColor = [UIColor clearColor];
    NSString *text = <#text#>;
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.lineSpacing = <#lineSpacing#>;
    NSDictionary *attr = @{
                           NSFontAttributeName: [UIFont <#font#>],
                           NSParagraphStyleAttributeName: style,
                           NSForegroundColorAttributeName: [UIColor <#color#>]
                           };
    attributedLabel.attributedText = [[NSAttributedString alloc] initWithString:text attributes:attr];
    [<#view#> addSubview:attributedLabel];



git管理

Xcode中的代码片段默认放在下面的目录中:
~/Library/Developer/Xcode/UserData/CodeSnippets 

####同步代码片段

上述目录设置成一个 Git 的版本库,将代码片段放到 Github 上。

git clone git@github.com:SilenceLee17/xcode_tool.git
cd xcode_tool
./setup_snippets.sh

扩展

系统自带的有一些代码片段,我们能不能修改?当然可以啦。

####Xcode内置代码片段目录

/Applications/Xcode.app/Contents/Frameworks/IDEKit.framework/Versions/A/Resources/SystemCodeSnippets.codesnippets

注意:Xcode5.1之前是在这个目录下

/Applications/Xcode.app/Contents/PlugIns/IDECodeSnippetLibrary.ideplugin/Contents/Resources/? SystemCodeSnippets.codesnippets

####SystemCodeSnippets.codesnippets浅析
该文件为plist格式xml文件描述文件。
IDECodeSnippetContents为代码片段的内容,修改即可达到目的。
IDECodeSnippetIdentifier唯一标示,重名即会覆盖。
IDECodeSnippetCompletionPrefix类似Completion Shortcut,键值留空可屏蔽该片段。

####Tips

  • 自定义目录不能有相同标识符的模板,否则Xcode启动后会崩溃。
  • 自定义母的模板标识符可以跟系统默认模板标识符相同,可以达到覆盖效果。
  • 若要使用自定义模板覆盖系统模板,则必须有DECodeSnippetUserSnippet字段,定义为true,否则Xcode启动后会崩溃。

补充2019/07/28

Xcode10的使用

Xcode升到最新的10.0以后,代码块移到了顶部导航栏上。
在这里插入图片描述

1、删除

选中你要删除个,按delete。

新增一些code snippet

Title: FIXME
Completion Shortcut: @fixme 
Completion Scopes: All

//FIXME: <#content#>
Title: TODO
Completion Shortcut: @todo 
Completion Scopes: All

//TODO: <#content#>
Title: property strong
Completion Shortcut: @ps 
Completion Scopes: All

@property (nonatomic, strong) <#type#> *<#name#>;
Title: property assign
Completion Shortcut: @pa
Completion Scopes: All

@property (nonatomic, assign) <#type#> *<#name#>;
Title: property weak
Completion Shortcut: @pw 
Completion Scopes: All

@property (nonatomic, weak) <#type#> <#name#>;
Title: viewDidAppear
Completion Shortcut: @viewdidappear 
Completion Scopes: All

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
}
Title: viewDidLoad
Completion Shortcut: @viewdidload 
Completion Scopes: All

- (void)viewDidLoad:(BOOL)animated {
    [super viewDidLoad:animated];
    
}
Title: NSNotificationCenter defaultCenter
Completion Shortcut: @notificationcenter 
Completion Scopes: All

[NSNotificationCenter defaultCenter]
Title: NSUserDefaults standardUserDefaults
Completion Shortcut: @userdefaults 
Completion Scopes: All

[NSUserDefaults standardUserDefaults]

脚本

脚本setup_snippets.sh。
其实是将原来的CodeSnippets拷贝至CodeSnippets.backup。
然后将Xcode的CodeSnippets软链接到该工程的CodeSnippets的文件夹下。

#! /bin/bash
mv ~/Library/Developer/Xcode/UserData/CodeSnippets ~/Library/Developer/Xcode/UserData/CodeSnippets.backup

#rm ~/Library/Developer/Xcode/UserData/CodeSnippets

SRC_HOME=`pwd`
ln -s ${SRC_HOME}/CodeSnippets ~/Library/Developer/Xcode/UserData/CodeSnippets
echo "done"

想法

1、快捷键为什么以@开头

一般情况还是希望以@打头,给出一种仪式感。

2、快键键为什么使用全称

例如viewdidload,为什么不使用vdl。
使用vdl需要一个映射。
Xcode自身的模糊匹配,能通过vdl找到viewdidload。

3、一些扩展想法

扫描工程,选取出使用最多一些方法。自动加到code snippet中。
自动学习,选取输入最多的方法。自动加到code snippet中。

工程地址

https://github.com/SilenceLee17/xcode_tool


#摘录:
http://blog.csdn.net/minjing_lin/article/details/52688736
https://segmentfault.com/a/1190000005073808
http://www.jianshu.com/p/91a58380fb42
http://www.cnblogs.com/zhoup/p/5016729.html
http://www.jianshu.com/p/499e315a7667
http://www.jianshu.com/p/de7806f6143b
http://www.cnblogs.com/LiLihongqiang/p/5934677.html
https://github.com/tangqiaoboy/xcode_tool
http://www.cocoachina.com/industry/20130604/6336.html
http://www.cocoachina.com/ios/20160127/15004.html
补充2019/07/28
http://mrpeak.cn/blog/xcode-easycode/
https://blog.csdn.net/lg767201403/article/details/82761448

  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值