Code Example 1: Creating buttons
❓ Какие способы создания Button существуют?
Button(action: {
print("Нажато")
}, label: {
Text("Нажми меня")
})
Button {
print("Нажато")
} label: {
Text("Нажми меня")
}
Button("Нажми меня") {
print("Нажато")
}
Button("Удалить", role: .destructive) {
print("Удаление")
}
Code Example 2: Button with state
❓ Как создать кнопку, которая изменяет состояние?
struct CounterView: View {
@State private var count = 0
var body: some View {
VStack(spacing: 20) {
Text("Счётчик: \(count)")
.font(.largeTitle)
Button("Увеличить") {
count += 1
}
Button("Сбросить") {
count = 0
}
}
}
}
Code Example 3: Button styles
❓ Какие встроенные стили кнопок есть в SwiftUI?
struct ButtonStyles: View {
var body: some View {
VStack(spacing: 20) {
Button("Automatic") { }
.buttonStyle(.automatic)
Button("Bordered") { }
.buttonStyle(.bordered)
Button("Bordered Prominent") { }
.buttonStyle(.borderedProminent)
Button("Borderless") { }
.buttonStyle(.borderless)
Button("Plain") { }
.buttonStyle(.plain)
}
}
}
Code Example 4: Button with icon
❓ Как создать кнопку с иконкой?
struct IconButtons: View {
var body: some View {
VStack(spacing: 20) {
Button {
} label: {
Label("Добавить", systemImage: "plus.circle.fill")
}
.buttonStyle(.borderedProminent)
Button {
} label: {
Image(systemName: "heart.fill")
.font(.title)
}
Button {
} label: {
HStack {
Image(systemName: "cart.fill")
Text("Купить")
Text("$9.99")
.fontWeight(.bold)
}
.padding()
.background(Color.blue)
.foregroundStyle(.white)
.cornerRadius(10)
}
}
}
}
Code Example 5: Disabled button
❓ Как отключить кнопку по условию?
struct DisabledButton: View {
@State private var username = ""
var body: some View {
VStack(spacing: 20) {
TextField("Имя пользователя", text: $username)
.textFieldStyle(.roundedBorder)
Button("Продолжить") {
print("Отправка: \(username)")
}
.buttonStyle(.borderedProminent)
.disabled(username.isEmpty)
}
.padding()
}
}
Code Example 6: Custom ButtonStyle
❓ Как создать кастомный стиль кнопки?
struct ScaleButtonStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
configuration.label
.scaleEffect(configuration.isPressed ? 0.95 : 1.0)
.opacity(configuration.isPressed ? 0.8 : 1.0)
.animation(.easeInOut(duration: 0.1), value: configuration.isPressed)
}
}
Button("Масштабируемая кнопка") { }
.buttonStyle(ScaleButtonStyle())