SwiftUI中如何预览处于按压状态的按钮?
预览SwiftUI按钮按压状态的方案
不需要添加预览专用变量,核心思路是复用ButtonStyle中的样式逻辑,直接手动传入isPressed=true来生成按压状态的视图。
步骤1:重构ButtonStyle,抽离可复用的样式布局
把ButtonViewStyle中依赖configuration.isPressed的布局逻辑抽成单独的可复用View,既保留原有ButtonStyle的功能,也能在预览里直接调用:
import SwiftUI struct ButtonViewStyle: ButtonStyle { let model: ButtonModel @ViewBuilder func makeBody(configuration: Configuration) -> some View { // 调用抽离的样式View,传入系统的按压状态 StyledButtonContent( label: configuration.label, model: model, isPressed: configuration.isPressed ) } // 抽离的可复用样式View @ViewBuilder func StyledButtonContent<Label: View>(label: Label, model: ButtonModel, isPressed: Bool) -> some View { label .padding(EdgeInsets(uiEdgeInsets: model.getPadding())) .foregroundColor(.red) .background(model.getBackgroundColor(isPressed: isPressed)) .cornerRadius(999) } }
步骤2:在预览中直接生成按压状态视图
在预览代码里,直接调用抽离的StyledButtonContent,手动传入isPressed=true,同时复用原有的Model配置:
#Preview { // 抽离Model,避免重复创建 let normalModel = TextButtonModel( textModel: TextModel(text: "Normal", color: .white, fontSize: .Body, fontWeight: .Semibold), color: .Primary, type: .Filled, size: .Normal ) let smallModel = TextButtonModel( textModel: TextModel(text: "Small", color: .white, fontSize: .Body, fontWeight: .Semibold), color: .Primary, type: .Filled, size: .Small ) return VStack { HStack(spacing: 16) { // 正常状态按钮 TextButtonView(model: normalModel) TextButtonView(model: smallModel) // 按压状态预览 ButtonViewStyle(model: normalModel).StyledButtonContent( label: TextView(model: normalModel.textModel), model: normalModel, isPressed: true ) } .padding() } }
这种方法完全不需要修改原有视图或模型的结构,只是通过抽离样式逻辑实现预览按压状态的需求。
内容的提问来源于stack exchange,提问作者tmontagnoni
相关产品推荐
相关产品推荐

