Animate a view to slide up and hide on tap in SwiftUI - ios

I created a banner modifier that displays a banner from the top. This animates well. However, when I tap to dismiss it, it does not animate at all, just hides even though the tap gesture action has withAnimation wrapping it.
struct BannerModifier: ViewModifier {
#Binding var model: BannerData?
func body(content: Content) -> some View {
content.overlay(
Group {
if model != nil {
VStack {
HStack(alignment: .firstTextBaseline) {
Image(systemName: "exclamationmark.triangle.fill")
VStack(alignment: .leading) {
Text(model?.title ?? "")
.font(.headline)
if let message = model?.message {
Text(message)
.font(.footnote)
}
}
}
.padding()
.frame(minWidth: 0, maxWidth: .infinity)
.foregroundColor(.white)
.background(.red)
.cornerRadius(10)
.shadow(radius: 10)
Spacer()
}
.padding()
.animation(.easeInOut)
.transition(AnyTransition.move(edge: .top).combined(with: .opacity))
.onTapGesture {
withAnimation {
model = nil
}
}
.gesture(
DragGesture()
.onChanged { _ in
withAnimation {
model = nil
}
}
)
}
}
)
}
}
struct BannerData: Identifiable {
let id = UUID()
let title: String
let message: String?
}
In the tap gesture, I wipe out the model but it does not animate. It only hides immediately. How can I animate it so it slide up which is opposite of how it slide down to display? It would be really nice if I can also make the drag gesture interactive so I can slide it out like the native notifications.

Removing view from hierarchy is always animated by container, so to fix your modifier it is needed to apply .animation on some helper container (note: Group is not actually a real container).
Here is corrected variant
struct BannerModifier: ViewModifier {
#Binding var model: BannerData?
func body(content: Content) -> some View {
content.overlay(
VStack { // << holder container !!
if model != nil {
VStack {
HStack(alignment: .firstTextBaseline) {
Image(systemName: "exclamationmark.triangle.fill")
VStack(alignment: .leading) {
Text(model?.title ?? "")
.font(.headline)
if let message = model?.message {
Text(message)
.font(.footnote)
}
}
}
.padding()
.frame(minWidth: 0, maxWidth: .infinity)
.foregroundColor(.white)
.background(Color.red)
.cornerRadius(10)
.shadow(radius: 10)
Spacer()
}
.padding()
.transition(AnyTransition.move(edge: .top).combined(with: .opacity))
.onTapGesture {
withAnimation {
model = nil
}
}
.gesture(
DragGesture()
.onChanged { _ in
withAnimation {
model = nil
}
}
)
}
}
.animation(.easeInOut) // << here !!
)
}
}
Tested with Xcode 12.1 / iOS 14.1 and test view:
struct TestBannerModifier: View {
#State var model: BannerData?
var body: some View {
VStack {
Button("Test") { model = BannerData(title: "Error", message: "Fix It!")}
Button("Reset") { model = nil }
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.modifier(BannerModifier(model: $model))
}
}

This is a slightly improoved version of the banner posted by Asperi
Hope it helps someone.
import SwiftUI
public class BannerData {
public enum BannerType {
case warning, error, success
var textColor: Color {
switch self {
case .warning:
return .black
case .error:
return .white
case .success:
return .white
}
}
var backgroundColor: Color {
switch self {
case .warning:
return .yellow
case .error:
return .red
case .success:
return .green
}
}
var icon: String {
switch self {
case .warning:
return "exclamationmark.triangle.fill"
case .error:
return "exclamationmark.circle.fill"
case .success:
return "checkmark.circle.fill"
}
}
}
var type: BannerType = .success
let title: String
let message: String?
public init(title: String, message: String? = nil, type: BannerType) {
self.title = title
self.message = message
self.type = type
}
}
public struct BannerModifier: ViewModifier {
#Binding var model: BannerData?
public init(model: Binding<BannerData?>) {
_model = model
}
public func body(content: Content) -> some View {
content.overlay(
VStack {
if model != nil {
VStack {
HStack(alignment: .firstTextBaseline) {
Image(systemName: model?.type.icon ?? BannerData.BannerType.success.icon)
VStack(alignment: .leading) {
Text(model?.title ?? "")
.font(.headline)
if let message = model?.message {
Text(message)
.font(.footnote)
}
}
Spacer()
}
.padding()
.frame(minWidth: 0, maxWidth: .infinity)
.foregroundColor(.white)
.background(model?.type.backgroundColor ?? .clear)
.cornerRadius(10)
.shadow(radius: 10)
Spacer()
}
.padding()
.transition(AnyTransition.move(edge: .top).combined(with: .opacity))
.onTapGesture {
withAnimation {
model = nil
}
}
.gesture(
DragGesture()
.onChanged { _ in
withAnimation {
model = nil
}
}
)
}
}
.animation(.spring())
)
}
}

Related

SwiftUI ScrollView won't let me scroll up

I'm trying to implement a chat feature, the relevant codes are simple enough
struct ContentView: View {
#State private var channelId = ""
#State private var message = ""
#ObservedObject var sig = SignalRService(urlStr: "\(API.HubsEndpoint)/hubs/theHub")
var body: some View {
VStack {
HStack {
TextField("Channel ID", text: $channelId) .textFieldStyle(.roundedBorder)
Button {
sig.invoke(method: "JoinRoom", arguments: [channelId]) { error in
print("joined")
if let err = error {
print(err)
}
}
} label: {
Text("Join")
}
.padding(5)
.background(Color.accentColor)
.foregroundColor(.white)
.cornerRadius(2)
}
.padding()
Spacer()
ScrollView {
ScrollViewReader { scrollView in
LazyVStack(alignment: .leading, spacing: 5) {
ForEach(sig.messages) { msg in
HStack(alignment: .top) {
Text(msg.user)
.font(.caption)
.bold()
Text(msg.message)
.font(.caption)
}
.id(msg.id)
.padding(20)
.background(.regularMaterial)
.foregroundColor(.white)
.cornerRadius(10)
}
}
.onChange(of: sig.messages.last) { newValue in
scrollView.scrollTo(newValue?.id)
}
}
.frame(height: UIScreen.main.bounds.height/4, alignment:.bottom)
}
.frame(height: UIScreen.main.bounds.height/4, alignment:.bottom)
.background(Color.black)
HStack {
TextField("Message", text: $message)
.textFieldStyle(.roundedBorder)
Button {
sig.invoke(method: "SendMessage", arguments: [message, channelId]) { error in
print("messaged")
if let err = error {
print(err)
}
else {
message = ""
}
}
} label: {
Image(systemName: "paperplane.fill")
}
.padding(5)
.background(Color.accentColor)
.foregroundColor(.white)
.cornerRadius(2)
}
.padding(.horizontal)
}
}
}
And the result: https://imgur.com/a/9JdPkib
It kept snapping to the bottom when I tried to scroll up.
I'm clipping the frame size and increased the padding to exaggerate the views, so it's easier to test.
Any idea what's causing the issue?

SwiftUI Custom Half Modal Calculator Not Working

I'm working on a math game and I would like to implement a small calculator in the background with a custom half modal.
The problem is that the inputted number is not updated unless you physically dismiss the modal and open it again. Although this is an extremely stressful calculator to use, I want to have the text updated immediately after a button is pressed just like a normal calculator (except the fact that it is in a half modal but still).
Please let me know if there is something I'm missing anything and here's my code to review...
struct PGQuestion1: View {
#State var show = false
#State var showA = false
#State var showB = false
#State var showC = false
#State var showSheet: Bool = false
#State var showSheetA: Bool = false
#State var showSheet2: Bool = false
#State private var chromaShift = false
#State var value = "0"
let buttons: [[CalcButton]] = [
[.clear, .negative, .percent, .divide],
[.seven, .eight, .nine, .multiply],
[.four, .five, .six, .subtract],
[.one, .two, .three, .add],
[.zero, .decimal, .equal]
]
#State var currentOperation: Operation = .none
#State var runningNumber = 0
var body: some View {
ZStack {
Color.indigo.ignoresSafeArea()
VStack {
VStack(alignment: .leading) {
HStack {
Image(systemName: "1.circle")
.foregroundColor(.white)
.font(.largeTitle)
.padding()
Spacer()
}
}
VStack {
Text("Solve the following:")
.foregroundColor(.white)
.font(.title2)
.fontWeight(.medium)
.padding(.bottom, 44)
Text("(54-9)÷5")
.foregroundColor(.white)
.font(.system(size: 60, design: .rounded))
.fontWeight(.medium)
.padding(.bottom, 45)
VStack(spacing: 0.01) {
ZStack {
VStack {
if showA {
Rectangle()
.fill(Color.purple.opacity(0.95))
.frame(maxWidth: .infinity, maxHeight: 100)
.cornerRadius(30)
.padding()
} else {
Rectangle()
.fill(Color.white.opacity(0.5))
.frame(maxWidth: .infinity, maxHeight: 100)
.cornerRadius(30)
.padding()
}
}
.onTapGesture {
showA.toggle()
self.showB = false
self.showC = false
}
Text("9")
.font(.largeTitle)
.foregroundColor(.white)
}
ZStack {
VStack {
if showB {
Rectangle()
.fill(Color.purple.opacity(0.95))
.frame(maxWidth: .infinity, maxHeight: 100)
.cornerRadius(30)
.padding()
} else {
Rectangle()
.fill(Color.white.opacity(0.5))
.frame(maxWidth: .infinity, maxHeight: 100)
.cornerRadius(30)
.padding()
}
}
.onTapGesture {
showB.toggle()
self.showA = false
self.showC = false
}
Text("52.2")
.font(.largeTitle)
.foregroundColor(.white)
}
HStack(spacing: 20) {
Button {
showSheet.toggle()
} label: {
VStack {
ZStack {
Circle()
.fill(Color.purple.opacity(0.8))
.frame(width: 80, height: 80)
.padding(.top, 13)
.padding(.leading, 28.5)
Image(systemName: "circle.grid.3x3.fill")
.foregroundColor(.white)
.font(.largeTitle)
.padding(.top, 13)
.padding(.leading, 28.5)
}
Text("Calculator")
.foregroundColor(.white)
.padding(.bottom)
.padding(.leading, 28.5)
}
}
.halfSheet(showSheet: $showSheet) {
ZStack {
Color.black.opacity(0.9).ignoresSafeArea()
VStack {
Spacer()
// Text display
HStack {
Spacer()
Text(value)
.bold()
.font(.system(size: 70))
.foregroundColor(.white)
.minimumScaleFactor(0.5)
}
.padding(.leading)
.padding([.top, .trailing], 23)
.padding(.bottom, 2)
// Our Buttons
ForEach(buttons, id: \.self) { row in
HStack(spacing: 12) {
ForEach(row, id: \.self) { item in
Button {
self.didTap(button: item)
} label: {
Text(item.rawValue)
.font(.system(size: 36))
.frame(width: self.buttonWidth(item: item), height: 55)
.scaledToFit()
.background(item.buttonColor)
.foregroundColor(.white)
.cornerRadius(95)
}
}
}
.padding(.bottom, 0.55)
.padding([.leading, .trailing], 20)
}
}
}
}
Button {
showSheet2.toggle()
} label: {
VStack {
ZStack {
Circle()
.fill(Color.purple.opacity(0.8))
.frame(width: 80, height: 80)
.padding(.top, 13)
Image(systemName: "book")
.foregroundColor(.white)
.font(.largeTitle)
.padding(.top, 13)
}
Text("Dictonary")
.foregroundColor(.white)
.padding(.bottom)
}
}
.halfSheet(showSheet: $showSheet2) {
ZStack {
Color.black.opacity(0.9).ignoresSafeArea()
VStack(alignment: .leading) {
HStack {
}
}
}
}
VStack {
if !show {
ZStack {
Circle()
.fill(Color.purple.opacity(0.8))
.frame(width: 80, height: 80)
.blur(radius: 10)
.padding(.top, 13)
.padding(.trailing)
Image(systemName: "info")
.foregroundColor(.black)
.font(.largeTitle)
.padding(.top, 13)
.padding(.trailing)
}
.onTapGesture {
withAnimation {
show.toggle()
}
}
} else {
ZStack {
Circle()
.fill(Color.purple.opacity(0.8))
.frame(width: 80, height: 80)
.blur(radius: 10.35)
.padding(.top, 13)
.padding(.trailing)
Text("Upgrade to Mathematically MAX")
.foregroundColor(.black)
.font(.system(size: 13))
.minimumScaleFactor(0.5)
.multilineTextAlignment(.center)
.padding(.top, 16)
.padding(1)
.padding(4)
.padding(5)
.padding(.trailing)
}
.onTapGesture {
withAnimation {
show.toggle()
}
}
}
Text("Intelligent Finding")
.foregroundColor(.black)
.font(.system(size: 12))
.padding(.top, 2)
.padding(.bottom)
.padding(.trailing)
}
}
.frame(maxWidth: .infinity, maxHeight: 140)
.background(Color.white.opacity(0.3))
.cornerRadius(40)
.padding()
}
}
HStack {
ZStack {
Text("Swipe to the next page")
.font(.title2)
.foregroundColor(Color.yellow)
.shadow(color: .white, radius: 10)
.hueRotation(.degrees(chromaShift ? 0 : 520))
.animation(Animation.linear(duration: 4).repeatForever(autoreverses: true))
.onAppear() {
self.chromaShift.toggle()
}
}
Image(systemName: "chevron.forward")
.font(.title2)
.foregroundColor(Color.yellow)
.shadow(color: .white, radius: 10)
.hueRotation(.degrees(chromaShift ? 0 : 520))
.animation(Animation.linear(duration: 4).repeatForever(autoreverses: true))
.onAppear() {
self.chromaShift.toggle()
}
}
Spacer()
}
}
}
func didTap(button: CalcButton) {
switch button {
case .add, .subtract, .multiply, .divide, .equal:
if button == .add {
self.currentOperation = .add
self.runningNumber = Int(self.value) ?? 0
} else if button == .subtract {
self.currentOperation = .subtract
self.runningNumber = Int(self.value) ?? 0
} else if button == .multiply {
self.currentOperation = .multiply
self.runningNumber = Int(self.value) ?? 0
} else if button == .divide {
self.currentOperation = .divide
self.runningNumber = Int(self.value) ?? 0
} else if button == .equal {
let runningValue = self.runningNumber
let currentValue = Int(self.value) ?? 0
switch self.currentOperation {
case .add:
self.value = "\(runningValue + currentValue)"
case .subtract:
self.value = "\(runningValue - currentValue)"
case .multiply:
self.value = "\(runningValue * currentValue)"
case .divide:
self.value = "\(runningValue / currentValue)"
case .none:
break
}
}
if button != .equal {
self.value = "0"
}
case .clear:
self.value = "0"
case .decimal, .percent, .negative:
break
default:
let number = button.rawValue
if self.value == "0" {
value = number
} else {
self.value = "\(self.value)\(number)"
}
}
}
func buttonWidth(item: CalcButton) -> CGFloat {
if item == .zero {
return ((UIScreen.main.bounds.width - (4*12)) / 4) * 2
}
return (UIScreen.main.bounds.width - (5*12)) / 4
}
func buttonHeight() -> CGFloat {
return (UIScreen.main.bounds.height - (5*12)) / 4
}
}
enum CalcButton: String {
case one = "1"
case two = "2"
case three = "3"
case four = "4"
case five = "5"
case six = "6"
case seven = "7"
case eight = "8"
case nine = "9"
case zero = "0"
case add = "+"
case subtract = "-"
case divide = "÷"
case multiply = "×"
case equal = "="
case clear = "AC"
case decimal = "."
case percent = "%"
case negative = "+/-"
var buttonColor: Color {
switch self {
case .add, .subtract, .multiply, .divide, .equal:
return .orange
case .clear, .negative, .percent:
return .gray
default:
return Color(UIColor(red: 55/255.0, green: 55/255.0, blue: 55/255.0, alpha: 1))
}
}
}
enum Operation {
case add, subtract, multiply, divide, none
}
extension View {
func halfSheet<SheetView: View>(showSheet: Binding<Bool>, #ViewBuilder sheetView: #escaping () -> SheetView) -> some View {
return self
.background(
HalfSheetHelper(sheetView: sheetView(), showSheet: showSheet)
)
}
}
struct HalfSheetHelper<SheetView: View>: UIViewControllerRepresentable {
var sheetView: SheetView
#Binding var showSheet: Bool
let controller = UIViewController()
func makeUIViewController(context: Context) -> UIViewController {
controller.view.backgroundColor = .clear
return controller
}
func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
let sheetController = CustomHostingController(rootView: sheetView)
if showSheet {
uiViewController.present(sheetController, animated: true) {
DispatchQueue.main.async {
self.showSheet.toggle()
}
}
}
}
}
class CustomHostingController<Content: View>: UIHostingController<Content> {
override func viewDidLoad() {
if let presentationController = presentationController as? UISheetPresentationController {
presentationController.detents = [
.medium(),
.large()
]
presentationController.prefersGrabberVisible = true
}
}
}
The problem is in your func halfSheet() and struct HalfSheetHelper. You have created a UIViewControllerRepresentable view, but it does not handle updates.
Once the sheet has already been shown, the sequence of events happening is:
Pressing a button triggers a change to self.value inside PGQuestion1.
SwiftUI re-renders PGQuestion1, and a new closure is passed to .halfSheet { ... } which uses the new value.
Since the HalfSheetHelper is UIViewRepresentable, SwiftUI calls your updateUIViewController() function. A completely new CustomHostingController is created. Then nothing else happens because showSheet is false.
To handle updates properly, I recommend you create a Coordinator class inside your HalfSheetHelper. The coordinator is a class that SwiftUI will keep alive as long as the view is being used, and it can maintain a persistent reference to the CustomHostingController. Then in updateUIViewController(), you can use the coordinator to access the hosting controller and re-assign its rootView with the newly updated sheet contents. For more on these techniques, see the Interfacing with UIKit tutorial.
I also changed how showSheet is handled so that it becomes false only once the sheet is dismissed. This required adding a custom onDismiss closure to the CustomHostingController which it calls in viewDidDisappear.
(There still seems to be a bug with the half-sheet, where if I swipe down to dismiss the sheet and then show it again, it appears fullscreen instead of half-screen. I'm not familiar enough with the presentationController/detents APIs to figure out why this is happening!)
struct HalfSheetHelper<SheetView: View>: UIViewControllerRepresentable {
var sheetView: SheetView
#Binding var showSheet: Bool
class Coordinator {
let dummyController = UIViewController()
let sheetController: CustomHostingController<SheetView>
init(sheetView: SheetView, showSheet: Binding<Bool>) {
sheetController = CustomHostingController(rootView: sheetView, onDismiss: { showSheet.wrappedValue = false })
dummyController.view.backgroundColor = .clear
}
}
func makeCoordinator() -> Coordinator {
return Coordinator(sheetView: sheetView, showSheet: $showSheet)
}
func makeUIViewController(context: Context) -> UIViewController {
return context.coordinator.dummyController
}
func updateUIViewController(_ uiViewController: UIViewController, context: Context) {
context.coordinator.sheetController.rootView = sheetView
if showSheet && uiViewController.presentedViewController == nil {
uiViewController.present(context.coordinator.sheetController, animated: true)
}
}
}
class CustomHostingController<Content: View>: UIHostingController<Content> {
var onDismiss: (() -> Void)?
convenience init(rootView: Content, onDismiss: #escaping () -> Void) {
self.init(rootView: rootView)
self.onDismiss = onDismiss
}
override func viewDidLoad() {
if let presentationController = presentationController as? UISheetPresentationController {
presentationController.detents = [
.medium(),
.large()
]
presentationController.prefersGrabberVisible = true
}
}
override func viewDidDisappear(_ animated: Bool) {
onDismiss?()
}
}

How can I add a badge to a leading navigationBarItems in SwiftUI and iOS 14?

How can I add a badge to navigationBarItems in SwiftUI and iOS 14?
I cannot find anything on the net...
I want for example add a badge over the leading navigationBarItems:
var body: some View {
NavigationView {
ZStack {
VStack(spacing: 0) {
Text("Peanut")
.padding(-10)
.navigationBarTitle(Text("HomeTitle"), displayMode: .inline)
.navigationBarItems(leading:
HStack {
NavigationLink(destination: Notifications()) {
Image(systemName: "bell")
.font(.system(size: 20))
}.foregroundColor(.white)
}, trailing:
HStack {
NavigationLink(destination: Settings()) {
Image(systemName: "gearshape")
.font(.system(size: 20))
}.foregroundColor(.white)
})
}
}
}
}
You can create a custom Badge view:
struct Badge: View {
let count: Int
var body: some View {
ZStack(alignment: .topTrailing) {
Color.clear
Text(String(count))
.font(.system(size: 16))
.padding(5)
.background(Color.red)
.clipShape(Circle())
// custom positioning in the top-right corner
.alignmentGuide(.top) { $0[.bottom] }
.alignmentGuide(.trailing) { $0[.trailing] - $0.width * 0.25 }
}
}
}
and use it as an overlay:
struct ContentView: View {
var body: some View {
NavigationView {
ZStack {
VStack(spacing: 0) {
Text("Peanut")
.padding(-10)
.navigationBarTitle(Text("HomeTitle"), displayMode: .inline)
.navigationBarItems(leading: leadingBarItems)
}
}
}
}
var leadingBarItems: some View {
NavigationLink(destination: Text("Notifications")) {
Image(systemName: "bell")
.font(.system(size: 20))
}
.foregroundColor(.primary)
.padding(5)
.overlay(Badge(count: 3))
}
}
Note
The badge view uses alignment guides for positioning. For more information see:
Alignment Guides in SwiftUI
Here's another example of custom badge
struct BadgeViewModifier: ViewModifier {
let text: String?
func body(content: Content) -> some View {
content
.overlay(alignment: .topTrailing) {
text.map { value in
Text(value)
.fixedSize(horizontal: true, vertical: false)
.font(.system(size: 14, weight: .semibold))
.foregroundColor(DS.Colors.white)
.padding(.horizontal, value.count == 1 ? 2 : 6)
.padding(.vertical, 2)
.background(
Capsule()
.fill(DS.Colors.red)
.if(value.count == 1) { $0.aspectRatio(1, contentMode: .fill) }
)
}
}
}
}
extension View {
func badge(value: String?) -> some View {
modifier(BadgeViewModifier(text: value))
}
#ViewBuilder func `if`<Result: View>(_ condition: Bool, closure: #escaping (Self) -> Result) -> some View {
if condition {
closure(self)
} else {
self
}
}
}

SwiftUI custom modal view transition lagging

I have a custom modal View which is part of the ZStack which overlays the other content when enabled.
When a button is pressed, I want the modal sheet to transition from the bottom edge of the device to the centre of the screen, which I have somewhat accomplished. However, the animation somewhat fails when dismissing the modal view, as seen in the provided video, and I'm having difficulties figuring out why this is.
The animation of the modal view I'm using is
.animation(Animation.spring().speed(1.5))
.transition(.move(edge: .bottom))
For the sake of completion, here is my modal view:
struct AddEventView: View {
#State var eventName: String = ""
#State var endDate = Date().addingTimeInterval(60)
#State var gradientIndex: Int = 0
#EnvironmentObject var model: Model
let existingEvent: Event?
let linearGradients: [LinearGradient] = Gradient.gradients.map {
LinearGradient(
gradient: $0,
startPoint: .topTrailing,
endPoint: .bottomLeading
)
}
/// This closure is invoked when the view is dimissed, with a newly created Event passed as its parameter.
/// If the user cancelled this action, `nil` is passed as the parameter
let onDismiss: (Event?) -> Void
var body: some View {
print("Redrawing AddEventView")
return VStack(spacing: 30.0) {
HStack {
Spacer().frame(width: 44)
Spacer()
Text(existingEvent == nil ? "Create Event" : "Edit Event")
.font(.title3)
.bold()
Spacer()
Button(action: {
onDismiss(nil)
}) {
Image(systemName: "xmark.circle.fill")
.imageScale(.large)
}
.frame(width: 44)
}
.padding(.bottom, 5)
.padding(.top, 8)
HStack {
Text("Name of Event").padding(.trailing, 20)
TextField("My Birthday", text: $eventName)
.frame(height: 35)
}
DatePicker(
"Date of Event".padding(toLength: 19, withPad: " ", startingAt: 0),
selection: $endDate,
in: Date()...
)
.frame(height: 35)
ColorChooser(
linearGradients,
selectedIndex: $gradientIndex
)
.frame(height: 75)
Button(action: {
let adjustedEnd = Calendar.current.date(bySetting: .second, value: 0, of: endDate)
let event = Event(
name: eventName,
start: existingEvent?.start ?? Date(),
end: adjustedEnd!,
gradientIndex: gradientIndex
)
onDismiss(event)
}) {
RoundedRectangle(cornerRadius: 13)
.frame(maxWidth: .infinity)
.frame(height: 42)
.overlay(
Text(existingEvent == nil ? "Add Event" : "Edit Event")
.foregroundColor(.white)
.bold()
)
.padding(.horizontal, 1)
}
.padding(.top, 8)
.disabled(self.eventName.isEmpty)
}
.padding(.all, 16)
.background(Color.white)
.cornerRadius(16)
.shadow(radius: 16)
.onAppear {
if let event = existingEvent {
self.eventName = event.name
self.endDate = event.end
self.gradientIndex = event.gradientIndex
}
}
}
}
and my ContentView:
struct ContentView: View {
#State var progress: Double = 0.0
#State var showModal: Bool = false
#State var showPopover: Bool = false
#State var modifiableEvent: Event?
#State var now: Date = Date()
#State var confettiView = ConfettiUIView()
#EnvironmentObject var model: Model
let timer = Timer.publish(every: 1, on: .current, in: .common).autoconnect()
let columns: [GridItem] = Array(repeating: GridItem(.flexible(), spacing: 10), count: 2)
var alertButtons: [Alert.Button] {
return Model.SortableKeyPaths.map { key, _ in
.default(Text(key)) { model.sortedKey = key }
}
}
func onEventEnd() {
self.confettiView.emit(with: [.text("🎉")])
AudioManager.shared.play("Success 1.mp4")
let taptics = UINotificationFeedbackGenerator()
taptics.notificationOccurred(.success)
}
var grid: some View {
LazyVGrid(columns: columns, spacing: 10) {
ForEach(model.events, id: \.self) { event in
SmallCardView(event: event)
.contextMenu {
Button(action: {
modifiableEvent = event
withAnimation {
self.showModal = true
}
}) {
Text("Edit")
Image(systemName: "slider.horizontal.3")
}
Button(action: {
model.removeEvent(event)
}) {
Text("Delete")
Image(systemName: "trash")
}
}
.animation(.linear)
}
if !showModal || modifiableEvent != nil {
AddEventButtonView() {
modifiableEvent = nil
self.showModal = true
}
} else {
Spacer().frame(height: 100)
}
}
.navigationBarTitle(Text("My Events"), displayMode: .large)
.navigationBarItems(
leading: Button(action: { }) {
Image(systemName: "ellipsis")
.imageScale(.large)
},
trailing: Button(action: { self.showPopover = true }) {
Image(systemName: "arrow.up.arrow.down").imageScale(.large)
}
.actionSheet(isPresented: $showPopover) {
ActionSheet(
title: Text("Sort Events"),
buttons: alertButtons + [.cancel()]
)
}
)
}
var body: some View {
return ZStack {
NavigationView {
ScrollView {
grid.padding(.horizontal, 16)
}
.padding(.top)
}
.brightness(self.showModal ? -0.1 : 0)
.blur(radius: self.showModal ? 16 : 0)
.scaleEffect(self.showModal ? 0.95 : 1)
if self.showModal {
AddEventView(existingEvent: modifiableEvent) { event in
if let event = event {
self.model.removeEvent(modifiableEvent)
self.model.addEvent(event)
}
withAnimation {
self.showModal = false
}
}
.padding(.horizontal, 16)
.zIndex(1.0)
.animation(Animation.spring().speed(1.5))
.transition(.move(edge: .bottom))
}
EmptyView().id("\(self.now.hashValue)")
}
.overlay(
UIViewWrapper(view: $confettiView)
.edgesIgnoringSafeArea(.all)
.allowsHitTesting(false)
)
.onReceive(timer) { _ in
if !showModal { self.now = Date() }
if model.events.contains(where: { -1...0 ~= $0.timeRemaining }) {
onEventEnd()
}
}
}
}

SwiftUI Form Icons

Sorry if this is a really stupid question and maybe offtopic, but I can't seem to find it anywhere.
I'm trying to do a simple settings section for my app and would like to add icons to my elements so users can easily understand what does each setting does. To achieve that, I used Horizontal Stacks (HStack) with an Image and a Label (Text).
This somehow does the trick but I'd like to know if there's a cleaner way to do this.
I'd also like to know how to adjust the separator between cells to stop on the label, and not continue until the end of the element.
As I'm not really good at explaining, here you have two images:
This is what I got
I'd like to have something similar to this
My code:
SettingsView.swift
struct SettingsView: View {
#State var age: Int = 0
var body: some View {
UITableView.appearance().separatorStyle = .singleLine
UINavigationBar.appearance().shadowImage = UIImage()
return NavigationView {
Form {
Section {
Picker(selection: .constant(1), label: HStack {
Image(systemName: "paintbrush")
.font(Font.system(size: 25, weight: .light))
Text("Editor Theme")
}) {
Text("Ayu Mirage").tag(1)
Text("Ayu Light").tag(2)
}
Stepper(value: self.$age,
in: 18...100,
label: {
HStack {
Image(systemName: "rectangle.stack")
.font(Font.system(size: 25, weight: .light))
Text("Number of snippets: \(self.age)")
}
})
NavigationLink(destination: NotificationSettingsView()) {
HStack {
Image(systemName: "app.badge")
.font(Font.system(size: 25, weight: .light))
Text("Notifications")
}
}
}
Section {
VStack(alignment: .leading, spacing: 5) {
Text("Mercury v1.0")
.font(.headline)
Text("Designed with ❤️ by amodrono")
.font(.footnote)
}.padding(.vertical, 5)
}
}
.navigationBarTitle("Hello")
.environment(\.horizontalSizeClass, .regular)
.navigationBarTitle(Text("Settings"), displayMode: .inline)
.navigationBarItems(leading: (
Button(action: {
}) {
Image(systemName: "xmark")
.font(.headline)
.imageScale(.large)
.foregroundColor(Color(UIColor(named: "adaptiveColor")!))
}
))
}
}
}
You can disable the separator from the tableview and add your own divider.
Something like this:
struct ContentView: View {
var body: some View {
UITableView.appearance().separatorStyle = .none
return NavigationView {
Form {
Section {
RowView(iconName:"rectangle.stack", text:"Some text")
RowView(iconName:"paintbrush", text:"Some other text", showDivider: false)
}
}
}
}
}
struct RowView: View {
var iconName: String
var text: String
var showDivider = true
var body: some View {
HStack(alignment: .firstTextBaseline) {
Image(systemName: iconName)
VStack(alignment: .leading) {
Text(text)
if showDivider {
Divider()
} else {
Spacer()
}
}
}
}
}
do you mean like this? (if yes, just switch darkmode on ;))
import SwiftUI
#available(iOS 13.0, *)
public struct DarkView<Content> : View where Content : View {
var darkContent: Content
var on: Bool
public init(_ on: Bool, #ViewBuilder content: () -> Content) {
self.darkContent = content()
self.on = on
}
public var body: some View {
ZStack {
if on {
Spacer()
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
.background(Color.black)
.edgesIgnoringSafeArea(.all)
darkContent.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity).background(Color.black).colorScheme(.dark)
} else {
darkContent
}
}
}
}
#available(iOS 13.0, *)
extension View {
#available(iOS 13.0, *)
public func darkModeFix(_ on: Bool = true) -> DarkView<Self> {
DarkView(on) {
self
}
}
}
struct ContentView: View {
#State var age: Int = 0
var body: some View {
UITableView.appearance().separatorStyle = .singleLine
UINavigationBar.appearance().shadowImage = UIImage()
return NavigationView {
Form {
Section {
Picker(selection: .constant(1), label: HStack {
Image(systemName: "paintbrush")
.font(Font.system(size: 25, weight: .light))
Text("Editor Theme")
}) {
Text("Ayu Mirage").tag(1)
Text("Ayu Light").tag(2)
}
Stepper(value: self.$age,
in: 18...100,
label: {
HStack {
Image(systemName: "rectangle.stack")
.font(Font.system(size: 25, weight: .light))
Text("Number of snippets: \(self.age)")
}
})
// NavigationLink(destination: NotificationSettingsView()) {
// HStack {
// Image(systemName: "app.badge")
// .font(Font.system(size: 25, weight: .light))
//
// Text("Notifications")
// }
// }
}
Section {
VStack(alignment: .leading, spacing: 5) {
Text("Mercury v1.0")
.font(.headline)
Text("Designed with ❤️ by amodrono")
.font(.footnote)
}.padding(.vertical, 5)
}
}
.navigationBarTitle("Hello")
.environment(\.horizontalSizeClass, .regular)
.navigationBarTitle(Text("Settings"), displayMode: .inline)
.navigationBarItems(leading: (
Button(action: {
}) {
Image(systemName: "xmark")
.font(.headline)
.imageScale(.large)
// .foregroundColor(Color(UIColor(named: "adaptiveColor")!))
}
))
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.environment(\.colorScheme, .dark)
.darkModeFix()
}
}

Resources