You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用函数或扩展优化SwiftUI中重复的视图修饰代码?

优化方案:复用SwiftUI组件修饰符与布局

一、复用单个组件的修饰符(View扩展)

针对Text和TextField重复的修饰逻辑,通过View扩展封装固定样式,所有视图都能直接调用。

1. Text样式扩展

extension Text {
    func customLabelStyle() -> some View {
        self
            .font(.callout)
            .padding()
            .fontWeight(.bold)
            .foregroundColor(.blue)
    }
}

2. TextField样式扩展

封装固定修饰符,将可变参数(如焦点绑定)作为入参保留:

// 先确保你的焦点枚举已定义
enum FocusField: Hashable {
    case int
}

extension TextField {
    func customInputStyle(focused: FocusState<FocusField?>.Binding, equals field: FocusField) -> some View {
        self
            .keyboardType(.numberPad)
            .focused(focused, equals: field)
            .textFieldStyle(.roundedBorder)
            .frame(width: 80)
            .padding()
            .cornerRadius(40)
    }
}

使用时只需替换重复代码:

// 原Text代码简化为
Text("ΔAirway Pressure").customLabelStyle()

// 原TextField代码简化为
TextField("cmH2O", text: $Paw)
    .customInputStyle(focused: $focusedField, equals: .int)

二、复用整个行布局(自定义View)

由于整个HStack的布局结构完全重复,直接封装成自定义View,进一步减少代码量:

struct ParameterInputRow: View {
    let title: String
    @Binding var inputValue: String
    @FocusState.Binding var focusedField: FocusField?
    
    var body: some View {
        HStack {
            Text(title)
                .customLabelStyle()
            Spacer()
            TextField("cmH2O", text: $inputValue)
                .customInputStyle(focused: $focusedField, equals: .int)
        }
    }
}

调用时只需传入必要参数:

VStack {
    ParameterInputRow(title: "ΔAirway Pressure", inputValue: $Paw, focusedField: $focusedField)
    ParameterInputRow(title: "ΔEsophageal Pressure", inputValue: $Pes, focusedField: $focusedField)
}

三、跨视图复用的可行性

上述两种方案都支持全项目复用:

  • View扩展只需放在项目公共文件(如ViewExtensions.swift)中,所有视图无需导入即可直接调用样式方法;
  • 自定义View默认支持同一模块内所有视图调用,若需跨模块使用,只需将自定义View标记为public即可。

补充:灵活扩展(可选)

如果需要适配不同场景,可给扩展添加可选参数调整样式:

extension Text {
    func customLabelStyle(color: Color = .blue) -> some View {
        self
            .font(.callout)
            .padding()
            .fontWeight(.bold)
            .foregroundColor(color)
    }
}

使用时可按需修改:Text("示例标题").customLabelStyle(color: .red)

内容的提问来源于stack exchange,提问作者Alfred Wong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 11:42:49