Теперь у меня есть эта кнопка:
Когда он нажат, я хочу, чтобы «фон» был удален, например:
Как бы я это сделал? Я не могу заставить его работать. Теперь я добавляю фон, используя ZStack, что тоже не так уж приятно, потому что мне нужно инициализировать Button дважды.
Это путь размножения:
import Foundation
import SwiftUI
struct TestButton<V: View>: View {
@Environment(\.colorScheme) var colorScheme: ColorScheme
let content: V
var foregroundStyle: Color? = nil
var body: some View {
ZStack {
Button(action: {} ) {
content
}
.padding(10)
.background(Color(red: 0, green: 0, blue: 255/255))
.applyDefaultCornerRadius()
.offset(y: 5)
Button(action: {}) {
content
}
.padding(10)
.background(Color.blue)
.applyDefaultCornerRadius()
.foregroundStyle(foregroundStyle ?? (colorScheme == .light ? Color.white : Color.black))
}
}
}
#Preview {
TestButton(content: Text(verbatim: "Test"))
}





Чтобы применять разные стили при нажатии кнопки, вам необходимо определить свой собственный ButtonStyle.
В вашем примере хорошо работает изменение TestButton из общей оболочки Button в ButtonStyle. Используйте модификатор .animation, если хотите управлять фактической анимацией. Скорость анимации может зависеть от нажатого состояния — возможно, вам захочется, чтобы анимация выполнялась медленнее при подъеме нажатия.
struct TestButton: ButtonStyle {
@Environment(\.colorScheme) var colorScheme: ColorScheme
var foregroundStyle: Color? = nil
func makeBody(configuration: Configuration) -> some View {
configuration.label
.foregroundStyle(foregroundStyle ?? (colorScheme == .light ? Color.white : Color.black))
.padding(10)
.background {
RoundedRectangle(cornerRadius: 6)
.fill(.blue)
.stroke(foregroundStyle ?? (colorScheme == .light ? Color.black : Color.white))
}
.offset(y: configuration.isPressed ? 0 : -5)
.background {
RoundedRectangle(cornerRadius: 6)
.fill(Color(red: 0, green: 0, blue: 255/255))
.stroke(Color(red: 0, green: 0, blue: 255/255))
}
.animation(
.spring(duration: configuration.isPressed ? 0.05 : 0.2),
value: configuration.isPressed
)
}
}
struct ContentView: View {
var body: some View {
Button {} label: {
Text("Test")
}
.buttonStyle(TestButton())
}
}

Это действительно хорошо, спасибо большое!!