懒人必备神器-Xcode代码块

3,403 阅读3分钟

每天都有新的需求,尤其是那些业务代码,都是重复性的劳动,写的就是莫名的烦躁。但是也没有办法,还是要完成工作的。最近就向同事推荐了释放双手的神器代码块,这样就留出多余的时间干其他事情。

一、使用Code Snippets

Xcode版本不同这个入口也不同,当前我用的Xcode12的版本是在Xcode界面的右上角,点击+号就会弹出如下界面。其实我们发现系统已经写好了很多代码块,可以先自己浏览观察下都有哪些代码块,还可以在Snippets栏输入搜索你想使用的,并且有OC和Swift两种语言的代码块

截屏2021-11-09 下午11.54.21.png

比如,发现有个叫"@interface-category"的代码块,在类里面输入@interface-category,就会自动生成这个代码,这样是不是效率很高,不用重复的去写这个功能的代码.

  • 输入的时候有联想,并且代码块前面都是{}标识的
  • 可以找到想使用的代码块,直接拖拽过来使用

截屏2021-11-10 上午12.03.06.png

截屏2021-11-10 上午8.56.32.png

二、自定义代码块

系统写好的代码块毕竟不能满足开发的需求,其实自己也可以添加一些适合自己的代码块,只是要注意命名和系统的名称有区分,这样就很容易敲出自定义的。方法也很简单,选中格式化代码,右键

截屏2021-11-10 下午5.47.46.png

点击了Create Code Snippet,就会出现这个页面,主要需要填写代码块名称、摘要、代码块简称。这个简称就是我们敲代码,把简称输入系统就会提示相应的代码块

截屏2021-11-10 下午5.50.31.png

这样我们自定义的代码块就设置好了。例如,我设置的代码块简称是xLabel。当敲写xl时,系统自动提示出现设置的代码块。同样双击,代码自动写好了。

截屏2021-11-10 下午5.53.14.png

自定义的代码块在~/Library/Developer/Xcode/UserData/CodeSnippets,可以进去看到

截屏2021-11-10 上午9.01.39.png

截屏2021-11-10 下午5.54.48.png

三、常用的代码块

平常在开发中,我们有很多经常敲的场景,比如:

  • 属性的定义,比如声明一个属性
@property (nonatomic, strong) <type> <name>;

@property (nonatomic, weak) <type> <name>;

@property (nonatomic, copy) <type> <name>;

@property (nonatomic, assign) <type> <name>;
  • UI控件的书写,比如UIView、UILabel、UIButton等等
    UIButton *button = [[UIButton alloc] init];
    button.backgroundColor = ;
    button.titleLabel.font = [UIFont systemFontOfSize:];
    [button setTitle: forState:UIControlStateNormal];
    [button setImage: forState: UIControlStateNormal];
    [button setTitleColor: forState:UIControlStateNormal];
    [button addTarget:self action: @selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:button];
  • 常用的方法,比如UITableView的代理方法
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
   return ;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"" forIndexPath:indexPath];
    return cell;
}

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

}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return ;
}
  • 等等
__weak typeof(self) weakSelf = self;

只要是经常用到的场景,业务代码都可以定义成适合自己的代码块,不要觉得添加的时候麻烦,所谓磨刀不误砍柴工。整体使用还是比较方便简单的,这个代码块不会因为Xcode的升级而升级可以放心添加。