SwiftUI自定义ButtonStyle动画调整:解决iOS14触控按下无动画问题
现象说明
在SwiftUI框架中实现自定义ButtonStyle,基于isPressed状态动态调整按钮视图的样式时,交互表现存在系统版本差异:
- iOS 13环境下,手指按下、抬起按钮的两个节点,均能正常触发平滑过渡动画
- iOS 14及以上测试/正式版环境中,仅手指抬起时会触发动画,按下瞬间没有任何过渡反馈,按钮样式直接跳变
复现代码
struct CustomButtonStyle: ButtonStyle { func makeBody(configuration: Self.Configuration) -> some View { configuration.label .scaleEffect(configuration.isPressed ? 0.5 : 1) } } struct CustomButton: View { var body: some View { Button(action: {}) { RoundedRectangle(cornerRadius: 10) .frame(width: 100, height: 100) .foregroundColor(.pink) } .buttonStyle(CustomButtonStyle()) } }
问题原因
iOS 14开始,SwiftUI对ButtonStyle的状态更新逻辑做了调整:默认isPressed的状态变更不属于自动动画上下文,系统不会为该状态变化自动关联过渡动画,仅用户手势结束(手指抬起)相关的状态变更会触发系统默认动画。
修复方案
为绑定isPressed状态的样式修饰,显式添加对应动画,指定动画的触发源为configuration.isPressed,代码修改如下:
struct CustomButtonStyle: ButtonStyle { func makeBody(configuration: Self.Configuration) -> some View { configuration.label .scaleEffect(configuration.isPressed ? 0.5 : 1) // 新增动画绑定逻辑 .animation(.easeOut(duration: 0.2), value: configuration.isPressed) } }
注意事项
- 该写法兼容iOS 13及以上所有系统版本,不需要额外做系统版本判断
- 若存在多个基于
isPressed的样式修改(如透明度、圆角、颜色变化),仅需添加一次绑定configuration.isPressed的animation修饰即可,不会影响其他状态的动画表现 - 不要使用无绑定value的隐式动画写法(如
.animation(.easeOut)),该写法会作用到视图的所有状态变更,引发其他不必要的动画异常
内容的提问来源于stack exchange,提问作者Jordan H
相关产品推荐
相关产品推荐

