SwiftUI中如何自定义EditButton()的外观样式?
首先明确:原生EditButton没有提供传入自定义Label的初始化接口,你示例中带label闭包的写法无法直接运行,不需要从零实现编辑状态切换的完整逻辑,可按需求选择以下两种方案:
- 基础样式修改(仅调整内置文字样式)
如果不需要替换按钮的文字/图标内容,仅修改字体、颜色、内边距这类通用属性,直接给EditButton()加对应修饰符即可:
EditButton() .font(.title) .foregroundColor(.red) .padding(.top)
这种方式只会修改系统默认的"Edit"/"Done"文字样式,无法替换成自定义图片、自定义布局。
- 完全自定义外观(推荐)
系统的编辑状态由\.editMode环境值统一管理,你只需要自定义按钮的UI,点击时切换这个环境值即可,和原生EditButton的逻辑完全一致,兼容List、ForEach的删除、排序等所有编辑相关能力,示例代码如下:
struct CustomEditButton: View { @Environment(\.editMode) private var editMode // 可根据需求自定义编辑/非编辑状态的展示内容 private var inactiveLabel: some View { Image(systemName: "plus.circle") .padding(.top) .font(.title) .foregroundColor(.red) } private var activeLabel: some View { Image(systemName: "checkmark.circle") .padding(.top) .font(.title) .foregroundColor(.green) } var body: some View { Button { withAnimation { editMode?.wrappedValue = editMode?.wrappedValue.isEditing == true ? .inactive : .active } } label: { editMode?.wrappedValue.isEditing == true ? activeLabel : inactiveLabel } } }
使用时直接用CustomEditButton()替换原来的EditButton()即可,不需要额外配置。
注意:不要尝试通过
.buttonStyle()、.labelStyle()等修饰符替换原生EditButton的内部标签,系统对EditButton做了特殊封装,这类修饰符不会覆盖它内置的文字内容。
内容的提问来源于stack exchange,提问作者Moriz Bühler
相关产品推荐
相关产品推荐

