- 首先需要定义一个Button并添加一个内嵌VStack视图,以便可以存放其他视图,例如文本等。
Button(action: {}, label: {
VStack {
// 添加其他视图
}
})
- 现在需要创建一个自定义修饰符,该修饰符将为按钮添加光环动画。 在此示例中,我们将使用ViewModifier来创建自定义修饰符。
struct AuraButtonModifier: ViewModifier {
let isOn: Bool
func body(content: Content) -> some View {
content
.overlay(
Circle()
.stroke(lineWidth: 10)
.scaleEffect(isOn ? 1.5 : 1)
.opacity(isOn ? 0 : 1)
.animation(Animation.easeInOut(duration: 1).repeatForever(autoreverses: false))
)
}
}
- 接下来应该在Button代码中添加修饰符 - AuraButtonModifier,并为其创建一个@State变量以便在动画中更改。
struct ContentView: View {
@State private var isOn = false
var body: some View {
Button(action: {}, label: {
VStack {
Text("按钮")
.font(.title)
.fontWeight(.bold)
}
}).modifier(AuraButtonModifier(isOn: isOn))
}
}
- 最后,可以创建一个定时器来定期切换isOn状态以启动和停止动画。
private let timer = Timer.publish(every: 2, on: .main, in: .common).autoconnect()
// ...
struct ContentView: View {
@State private var isOn = false
var body: some View {
Button(action: {}, label: {
VStack {
Text("按钮")
.font(.title)
.fontWeight(.bold)
}
}).modifier(AuraButtonModifier(isOn: isOn))
.onReceive(timer) { _ in
self.isOn.toggle()
}
}
}