Xcode自动格式化代码

本文介绍了如何在Xcode中安装和配置Clang Format,包括通过Alcatraz安装,设置代码风格,配置快捷键,以及如何使用快捷键进行代码格式化。同时,提供了相关的参考链接以便进一步了解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

安装Clang Format

通过Alcatraz安装

配置

Edit |Clang Format 菜单中提供了几种预定义的格式化选项,其中 WebKit 是最接近官方Objective-C代码风格,不同的是函数名后的花括号会换行,*靠近类型名,例如:UIButton* signInButton;

File 选项为自定义格式化,如果想和官方代码风格一致,首先创建文件名为 .clang-format 文件,粘贴如下内容:


BasedOnStyle: WebKit
AccessModifierOffset: -2
ConstructorInitializerIndentWidth: 4
AlignEscapedNewlinesLeft: false
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false
AllowShortFunctionsOnASingleLine: false
AlwaysBreakTemplateDeclarations: false
AlwaysBreakBeforeMultilineStrings: false
BreakBeforeBinaryOperators: false
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false
BinPackParameters: true
ColumnLimit: 0
IndentWidth: 4
ConstructorInitializerAllOnOneLineOrOnePerLine: false
DerivePointerBinding: false
ExperimentalAutoDetectBinPacking: false
IndentCaseLabels: true
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCSpaceAfterProperty: true
ObjCSpaceBeforeProtocolList: true
PenaltyBreakBeforeFirstCallParameter: 19
PenaltyBreakComment: 300
PenaltyBreakString: 1000
PenaltyBreakFirstLessLess: 120
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 60
PointerBindsToType: false
SpacesBeforeTrailingComments: 1
Cpp11BracedListStyle: true
Standard: Cpp11
TabWidth: 8
UseTab: Never
BreakBeforeBraces: Attach 
IndentFunctionDeclarationAfterType: true
SpacesInParentheses: false
SpacesInAngles:  false
SpaceInEmptyParentheses: false
SpacesInCStyleCastParentheses: false
SpacesInContainerLiterals: true
SpaceBeforeAssignmentOperators: true
ContinuationIndentWidth: 4
CommentPragmas:  '^ IWYU pragma:'
SpaceBeforeParens: ControlStatements

如果想函数花括号对齐,可以将 BreakBeforeBraces 设置为 Stroustrup

可以将 .clang-format 拷贝到项目主目录下,也可以拷贝到 ~/ 目录下。两者不同是:前者只对当前项目使用自定义的格式化,后者对当前用户的所有项目。

配置快捷键

打开 系统偏好设置 | 键盘 | 快捷键 | 应用快捷键 ,单击 + 添加应用程序快捷键(Ctrl+Alt+F),如下图:

1

用相同的方法在为 Format File in Focus 添加快捷键(Ctrl+Shift+Alt+F),完成后如下图:

2

添加完成后,Xcode中的 Clang Format 菜单如下图:

3

使用

完成配置并且添加对应快捷键后,可以按 Ctrl+Alt+F 格式化当前选择代码,也可以 Ctrl+Shift+Alt+F 格式化当前光标所在文件的所有代码。

参考链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值