Xcode 使用 clang-format 格式化 OC 代码

  1. 将 Xcode 内置的 clang-format 工具加入环境变量, 位置通常在 /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin 目录下,或者执行 xcrun --find clang-format 查找其路径;
  2. 在 iOS 项目根目录创建 .clang-format 文件,复制粘贴以下内容,使代码格式化时遵循 Google OC 代码风格指南 规则;
     # clang-format for Objective-C, based on Google Style, validated for v21.x
     Language:        ObjC
     BasedOnStyle:    Google
    
    # 基础格式
    ColumnLimit:     100
    IndentWidth:     4
    UseTab:          Never
    PointerAlignment: Right
    AccessModifierOffset: -2
    
    # 大括号样式 (Attach)
    BreakBeforeBraces: Attach
    BraceWrapping:
    AfterFunction: true
    
    # 短语句允许单行的规则
    AllowShortFunctionsOnASingleLine: None
    AllowShortIfStatementsOnASingleLine: Never
    AllowShortLoopsOnASingleLine: false
    
    # 连续声明的对齐
    AlignConsecutiveDeclarations: Consecutive
    # Objective-C 特定选项
    ObjCBlockIndentWidth: 4
    ObjCSpaceAfterProperty: true
    ObjCSpaceBeforeProtocolList: true
    
    # 注释处理
    ReflowComments: true
    MaxEmptyLinesToKeep: 1
    
    # 其他
    SortIncludes:    true
    SpaceBeforeParens: ControlStatements
    
  3. $HOME(可以是任意位置,这里是用户目录) 下创建 clang-format-xcode.sh 文件,复制粘贴保存以下内容:
    #!/bin/zsh
    # 检查是否有 clang-format 工具
    if ! command -v clang-format &> /dev/null; then
        osascript -e 'display notification "clang-format not found" with title "Format Error"'
        exit 1
    fi
    
    # 获取 Xcode 当前编辑区打开的文件
    FILE_PATH=$(osascript <<EOF
    tell application "Xcode"
        if (count source documents) > 0 then
            return path of last source document
        else
            return ""
        end if
    end tell
    EOF
    )
    
    if [ -z "$FILE_PATH" ]; then
        osascript -e 'display notification "No active file in Xcode" with title "Format Error"'
        exit 1
    fi
    
    # 格式化文件
    if [[ "$FILE_PATH" == *.m || "$FILE_PATH" == *.h || "$FILE_PATH" == *.mm ]]; then
        clang-format -i -style=file "$FILE_PATH"
        osascript -e "display notification \"$FILE_PATH\" with title \"Formatted\""
    else
        osascript -e "display notification \"$FILE_PATH\" with title \"Format Skipped\""
    fi
    
  4. 在 Xcode 中创建 behavior 并配置快捷键;
    image.png

    image.png

    image.png

    image.png

    image.png

    image.png

    选择上面创建的 clang-format-xcode.sh 文件路径,点击 Done.
  5. 打开一个 OC 文件,按 Alt+Cmd+b 按键,即可看到 clang-format 按照 .clang-format 配置的规则自动格式化 OC 代码的效果。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容