【问题标题】:SwiftUI destructive Button styleSwiftUI 破坏性按钮样式
【发布时间】:2020-04-18 13:59:21
【问题描述】:

有没有办法在 SwiftUI 中获得破坏性的 Button 样式? 我知道我可以为ContextMenu 执行此操作,但我没有找到“正常”Button 的方法。

干杯

【问题讨论】:

    标签: button swiftui


    【解决方案1】:

    iOS 15

    从 iOS 15 开始,您可以(并且应该!)为每个按钮分配一个 Role,例如:

    Button("Delete", role: .destructive) {
         deleteSomething()
    }
    

    将角色分配给按钮有助于系统为使用该按钮的每个上下文应用正确的样式(例如 this example for a context menu

    更多自定义

    您可以创建修饰符的组合来创建所需的样式。

    演示

    上例代码:

    VStack {
                
          Button("Plain", role: .none, action: { })
          .buttonStyle(PlainButtonStyle())
    
          Button("Automatic", role: .none, action: { })
          .buttonStyle(.automatic)
    
          Button("Log out", role: .cancel, action: { })
          .buttonStyle(BorderedButtonStyle())
          .tint(.yellow)
    
          // with controlSize
          Button("Cancel", role: .cancel, action: { })
          .buttonStyle(.borderless)
          .controlSize(.small)
          .tint(.yellow)
    
          Button("Delete", role: .destructive, action: { })
          .buttonStyle(.bordered)
          .controlSize(.regular)
    
          // with controlProminence
          Button(role: .destructive, action: { }, label: {
              Text("Exit").frame(maxWidth: .infinity)
    
          })
          .buttonStyle(.bordered)
          .controlSize(.large)
          .controlProminence(.increased)
    
          //with BorderedShape
          Button(role: .destructive, action: { }, label: {
              Text("Wow shape").frame(maxWidth: .infinity)
          })
          .buttonStyle(BorderedButtonStyle(shape: .capsule))
          .controlSize(.large)
          .controlProminence(.increased)
          .tint(.purple)
    }
    

    【讨论】:

      【解决方案2】:

      对于Button

      Button("Tap") {
          // do something
      }
      .foregroundColor(.red)
      

      对于Alert

      Alert(
          title: Text("Hi"),
          message: Text("Do it?"),
          primaryButton: .cancel(Text("Cancel")),
          secondaryButton: .destructive(Text("Delete")) {
              // do something
          }
      )
      

      ActionSheet 也是如此。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-07
        • 2021-01-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-05
        • 1970-01-01
        相关资源
        最近更新 更多