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

iOS 18中SwiftUI的List内Toggle无法占满屏幕宽度问题

解决SwiftUI List中View无法占满屏幕宽度的问题

问题原因

SwiftUI的List默认会为行内容添加内边距,且Toggle组件在List中的布局行为和单独显示时不同,仅添加.frame(minWidth: .infinity)可能因未指定对齐方式或List样式限制而无法生效。

解决方案

方案1:给Toggle添加占满宽度的frame并指定对齐方式

修改TodoRow的布局,为Toggle添加frame(minWidth: .infinity, alignment: .leading),强制其占满可用宽度并左对齐:

struct TodoRow: View {
    @Binding var todo: Todo

    var body: some View {
        Toggle(isOn: $todo.isDone) {
            Text(todo.content ?? "")
        }
        .frame(minWidth: .infinity, alignment: .leading)
        .border(.red)
        .toggleStyle(.switch)
    }
}

方案2:配合List的plain样式

如果使用默认List样式仍有内边距,可将List设置为.plain样式,减少默认内边距:

struct ContentView: View {
   @State var td1 = Todo(content: "Hello Todo World 20240706T15:23:42.256Z", isDone: false)

    var body: some View {
        List {
            TodoRow(todo: $td1)
            TodoRow(todo: $td1)
        }
        .listStyle(.plain)
        .border(.green)
        
        TodoRow(todo: $td1)
            .border(.blue)
    }
}

方案3:用HStack包裹实现完全自定义宽度

若上述方法仍不生效,可将Toggle放入HStack中,让HStack占满整个行宽度:

struct TodoRow: View {
    @Binding var todo: Todo

    var body: some View {
        HStack {
            Toggle(isOn: $todo.isDone) {
                Text(todo.content ?? "")
            }
            .toggleStyle(.switch)
        }
        .frame(minWidth: .infinity, alignment: .leading)
        .border(.red)
    }
}

内容的提问来源于stack exchange,提问作者Sébastien Stormacq

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 10:33:13