通常我們建立的檔案(UIViewController
為例)預設是這樣的

但是我們通常都有自己的程式碼規範 比如#pragama mark - 功能分類
怎麼才能讓自己建立的檔案都預設帶上這些程式碼規範呢?
1. 定位XCode 模版檔案路徑
在Finder 中Shit+Command+G 貼上下面路徑
/Application/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/Library/Xcode
然後按照下圖的路徑進入 Cocoa Touch Class.xctemplate
資料夾

這個資料夾下面的就是XCode自帶的那些模版檔案了。
這裡AppleWatch、Playground 也都是對應Command+N的時候出來的對應模版.
Project Templates 是新建工程的時候出來的介面。
所以如果你在File Templates資料夾下面新建一個檔案的時候,你在Command + N 介面的也會看到新的內容。
2. 建立自定義模版檔案
下面我們開啟UIViewControllerSwift
或者UIViewControllerObjective-C
檔案, 一個是Swift中建立的UIViewController
一個是Objective-C
中。

UIViewController
模版了!
在XCode資料夾下面的資料夾和檔案都是有許可權限制,需要輸入密碼(開機密碼)來授予許可權。
接下來我們在UIViewControllerObjective-C
資料夾的同級資料夾(Cocoa Touch Class.xctemplate)下,複製UIViewControllerObjective-C
資料夾然後貼上。把這個資料夾改成你的自定義基類名稱。
比如你的基類叫CustomBaseViewController
,並且你想在OC
中用。那麼你現在的資料夾名字就該叫CustomBaseViewControllerObjective-C

這裡面的.h和.m 檔案就是模版檔案。我們開啟__FIELBASENAME__.m
然後修改一下,可以把下面的程式碼複製進去做實驗。
//___FILEHEADER___
#import "___FILEBASENAME___.h"
@interface ___FILEBASENAMEASIDENTIFIER___ ()
@end
@implementation ___FILEBASENAMEASIDENTIFIER___
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - 我是個不正經的檔案
@end
複製程式碼
儲存一下,我們進行下一步。
3. 讓XCode識別它
到現在我們模版已經建立好了,接下來怎麼讓XCode也識別它呢?

修改TemplateInfo.plist
屬性!
因為XCode資料夾的許可權限制問題,直接修改會比較麻煩(當然你也可以把資料夾和檔案的許可權改一下)。可以把這個檔案複製到別的地方,比如桌面,改完了再複製進來。
檔案許可權修改 右鍵->簡介 頁面底部,把everyone許可權改成讀寫
開啟長這個樣子。

UIViewController


Suffixes
是這個檔案建立的時候的字尾
比如你想這個給你的所有繼承CustomBaseViewController
的檔案都有以Controller
為字尾

這時候在XCode中建立檔案的時候


大功告成!
如果最後建立的時候有問題,重啟以下XCode即可!