直接看代码案例快速入手SwiftUI
本文介绍Button,Image,Toggle。
🎉下载GitHub仓库,直接体验
Button
struct ButtonContentView: View {
@GestureState private var isPressed = false
@State private var isButtonEnabled = false
var body: some View {
VStack {
Button("Click me", action: {
print("Button clicked")
})
Button(action: {
print("Button clicked")
}) {
Text("Custom button")
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(10)
}
Button(action: {
print("Image button clicked")
}) {
Image(systemName: "star.fill")
}
Button(action: {
print("Image text button clicked")
}) {
HStack {
Image(systemName: "star.fill")
Text("Image text button")
}
}
Button(action: {
print("Button clicked")
}) {
Text("Long press button")
.scaleEffect(isPressed ? 0.5 : 1)
.animation(.easeInOut(duration: 0.9), value: isPressed)
}
.simultaneousGesture(LongPressGesture(minimumDuration: 0.5)
.updating($isPressed) { value, state, _ in
state = value
print(value)
print("LongPress button clicked")
}
)
Button(action: {
print("Click on the enable/disable button")
}) {
Text("Enable/Disable button")
}
.disabled(!isButtonEnabled)
}
}
}
struct ButtonContentView_Previews: PreviewProvider {
static var previews: some View {
ButtonContentView()
}
}
Image
struct ImageContentView: View {
var body: some View {
VStack {
Image("moon")
Image(systemName: "star.fill")
Image("moon")
.renderingMode(.original)
Image("moon")
.resizable()
.frame(width: 100, height: 100)
// Image("moon")
// .resizable()
// .scaledToFit()
// Image("moon")
// .resizable()
// .scaledToFill()
Image("desk")
.frame(width: 100, height: 100)
.clipped()
// Image("moon")
// .resizable()
// .clipShape(Circle())
Image("moon")
.shadow(color: .gray, radius: 5, x: 0, y: 5)
Image("moon")
.opacity(0.5)
}
}
}
struct ImageContentView_Previews: PreviewProvider {
static var previews: some View {
ImageContentView()
}
}
Toggle
struct ToggleContentView: View {
@State private var isOn = false
var body: some View {
VStack {
Toggle("Switch", isOn: $isOn)
Toggle(isOn: $isOn) {
Text("Custom switch")
}
.toggleStyle(SwitchToggleStyle(tint: .red))
HStack {
Text("Horizontal arranged switch").lineLimit(1)
Spacer()
Toggle("", isOn: $isOn)
}
Toggle("Switch", isOn: $isOn)
.onChange(of: isOn) { value in
print("Change in on/off status: \(value)")
}
}
}
}
struct ToggleContentView_Previews: PreviewProvider {
static var previews: some View {
ToggleContentView()
}
}