2.4.1 控件-按钮

目录

按钮样式

Button 可以通过字符串或 view 构建,需要注意的是,通过字符串构建 Button 时, .frame 是无法扩大点击范围的。因为 frame 的作用是给父视图提供尺寸信息作布局用,我们可以在 frame 的基础上更改 button 的背景,但 button 自身的尺寸依然是由自身内容(字符串)决定的。对于简单的按钮可以直接通过字符串构建,系统也提供了内置的按钮样式。如需更丰富的样式,推荐使用 view 构建,或是自定义按钮样式。

在构建方法中可选传 role: ButtonRole? 表明按钮的作用,目前的作用类型有 .cancel 和 .destructive。一般用于模态场景,比如 alert 或者 confirmDialog。

系统内置了多种样式(ButtonStyle),效果参见示例。

iOS 上如果在 Form 或者 List 中使用按钮而不指定样式,button 的可点击范围会自动扩展至整个 item,使用 .buttonStyle(.borderless) 可以解除这一附加效果。

> 查看示例

内置的 ButtonStyle 默认使用主题色 accentColor 渲染,使用 .tint 方法可以指定主题色,不过它可能会覆盖指定 role 的部分按钮样式。

在 《App 入口与配置》 也提到过 accentColor 和 tint 的使用,其它场景类同,后文不再赘述。

自定义样式

SwiftUI 中的许多视图都内置了样式,比如 Button 通过 .buttonStyle 设置 ButtonStyle,List 通过 .listStyle 设置 ListStyle,Picker 通过 .pickerStyle 设置 PickerStyle。ButtonStyle、ListStyle 以及 PickerStyle 等,统统都是协议,内置样式都是通过实现相应的协议来给视图添加样式的,自定义样式也不例外。这也充分体现了 Swift 面向协议编程的理念,本质上其实是设计原则中的 DIP(依赖倒置原则)。

以下介绍的自定义按钮样式的思路可延用至其它视图的自定义样式。

在自定义支持多种模式的视图或功能时,亦可借鉴这一思路先定义好协议并预置一些默认实现,调用方可以使用预置的模式,也能通过协议自定义模式进行扩展。在提供灵活便利的同时,保持了和官方一致的 API 风格,对开发者是非常友好的。

言归正传,通过官方文档可以看到 Button 有如下两个方法变更样式:

1
2
3
func buttonStyle<S>(_ style: S) -> some View where S : ButtonStyle

func buttonStyle<S>(_ style: S) -> some View where S : PrimitiveButtonStyle

ButtonStyle 和 PrimitiveButtonStyle 这两个协议的定义几乎一样,唯一的区别是 ButtonStyle 内部有一个表示按钮是否按下的 Bool 类型属性 isPressed,而 PrimitiveButtonStyle 内部有一个 trigger() 方法供我们自定义交互。

自定义 ButtonStyle

如下是一个自定义的 ShadowButtonStyle,实现的效果是默认状态下是外阴影,按下的时候是内阴影,而且按钮背景和文字颜色也会变化。同时,按下按钮时会有个简单的动画效果。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
fileprivate struct ShadowButtonStyle: ButtonStyle {
  let radius: CGFloat
  
  func makeBody(configuration: Configuration) -> some View {
    // configuration.label 是按钮实体
    configuration.label
      .padding()
      // configuration.isPressed 表示按钮是否按下
      .foregroundColor(configuration.isPressed ? .gray : .white)
      .background(
        Capsule()
          .fill(.shadow(
            configuration.isPressed
            ? .inner(radius: radius)
            : .drop(radius: radius)
          ))
          .foregroundStyle(
              .linearGradient(
                colors: configuration.isPressed
                ? [.blue, .purple]
                : [.orange, .red],
                startPoint: .topLeading,
                endPoint: .bottomTrailing)
          )
      )
      .animation(.default, value: configuration.isPressed)
  }
}

我们可以这样调用:

1
.buttonStyle(ShadowButtonStyle(radius: 5))

但不够便捷,于是给 ButtonStyle 扩展一个静态方法:

1
2
3
4
5
fileprivate extension ButtonStyle where Self == ShadowButtonStyle {
  static func shadow(radius: CGFloat) -> Self {
    .init(radius: radius)
  }
}

这样在调用的时候通过点语法即可获取到编译器的智能提示。

自定义 PrimitiveButtonStyle

依样画葫芦,自定义一个双击才会生效的按钮样式:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
fileprivate struct DoubleTapButtonStyle: PrimitiveButtonStyle {
  @State private var scale: Double = 1.0
  @State private var isTrigger = true
  
  func makeBody(configuration: Configuration) -> some View {
    configuration.label
      .padding()
      .foregroundColor(.white)
      .background(Color.blue)
      .cornerRadius(10)
      .scaleEffect(isTrigger ? 1.0 : 1.1)
      .gesture(
        TapGesture(count: 2)
          .onEnded {
            configuration.trigger()
            isTrigger = false
            withAnimation(.spring(dampingFraction: 0.5)) {
              isTrigger = true
            }
          }
      )
  }
}

fileprivate extension PrimitiveButtonStyle where Self == DoubleTapButtonStyle {
  static var doubleTap: Self { Self() }
}

如示例所示,双击按钮时左边的计数才会加一。