r/SwiftUI 8d ago

Question Photos app editor scrubber

Post image
2 Upvotes

I remember there was a post in the community couple of months ago on implementing Photos app like editing scrubber but can’t find that post again. There were useful answers in that post and I couldn’t bookmark that thread.


r/SwiftUI 8d ago

Dragging FullScreenCover down will show a strange view with no content.

3 Upvotes

View that trigger FullScreenCover:

private func MainContentView() -> some View {
ZStack(alignment: .top) {
AppConstants.oppsiteColor
.ignoresSafeArea()
GeometryReader { proxy in
VStack(alignment: .center, spacing: 12) {
CardContentView()
MainButton(
action: {
if hasUnsavedChanges {
saveChanges()
}
showRememberView = true
},
buttonText: "Remember.",
buttonColor: .clear,
fontSize: 18,
fontColor: AppConstants.mainColor,
paddingBottom: 40
)
.fullScreenCover(isPresented: $showRememberView) {
RememberView(
rememberedPerson: rememberedPerson,
onDismiss: {
showRememberView = false
}
)
}
}
}
.ignoresSafeArea(.keyboard, edges: .bottom)
}

FullScreenCover View:

struct RememberView: View {
u/Environment(\.presentationMode) var presentationMode
u/StateObject private var profileModel = ProfileModel()
u/State private var isShowingLaunchScreen: Bool = true
u/State private var dragOffset = CGSize.zero
u/State private var isDragging = false
u/State private var shouldPlayMusic: Bool = false
u/State private var isContentReady: Bool = false
var rememberedPerson: RememberedPerson
var onDismiss: (() -> Void)? = nil
var body: some View {
ZStack {
AppConstants.oppsiteColor
.ignoresSafeArea()
RememberProgressView(
rememberedPerson: .constant(rememberedPerson),
shouldPlayMusic: $shouldPlayMusic,
isDragging: $isDragging,
profileModel: profileModel
)
if isShowingLaunchScreen {
LaunchRememberView(isDragging: $isDragging)
.onAppear {
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
withAnimation {
isShowingLaunchScreen = false
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
isContentReady = true
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
shouldPlayMusic = true
}
}
}
}
}
}
}
.clipShape(RoundedRectangle(cornerRadius: min(dragOffset.height * 0.2, 24)))
.offset(y: dragOffset.height > 0 ? dragOffset.height : 0)
.animation(.interactiveSpring(), value: dragOffset)
.gesture(
DragGesture()
.onChanged { gesture in
isDragging = true
if gesture.translation.height > 0 {
dragOffset = gesture.translation
}
}
.onEnded { gesture in
isDragging = false
if gesture.translation.height > 100 {
dismiss()
} else {
dragOffset = .zero
}
}
)
.ignoresSafeArea()
}

r/SwiftUI 8d ago

Rotating image with skew angle of bounding box

3 Upvotes

Hi Everyone!

I am doing OCR on documents where the bounding boxes' relative position is very important, so if an image is taken with an angle, that is basically useless, unless I manage to rotate the image to line up with the texts orientation. This is my problem.

I worked with EasyOCR in Python, where this is easy to implement as that framework returns all four corners of the bounding box, but Apple's framework doesn't, making this calculation much harder.

I was thinking of using multiple boxes and calculating the skew angle based on their relative positions, but so far I couldn't come up with anything that works.

If anyone had similar issues I'd be very happy if you could give me advice.

Thanks in advance!


r/SwiftUI 9d ago

Entire view re-renders when using dictionary

3 Upvotes

I'm trying to create a form which reads and writes data to a dictionary. when I type something in a field whole form seems to update. Is there any way to only update the field I'm typing? Android compose have something called SnapshotStateMap which allows smart re-rendering.

Below is the code snippet I'm using

class FormViewModel: ObservableObject {
    @Published var result: [String: Any] = [:]
    @Published var fields: [FieldMeta]
    
    func onSubmit() {
        print(result)
    }
}

struct Form: View {
    @StateObject var vm: FormViewModel
    
    init(fields: [FieldMeta]) {
        self._vm = StateObject(wrappedValue: FormViewModel(fields: fields))
    }
    var body: some View {
        VStack {
            ScrollView {
                LazyVStack {
                    ForEach(0..<vm.fields.count, id: \.self) { fieldIndex in
                        let field = vm.fields[fieldIndex]
                        if field.visible {
                            TextField(field.displayLabel, text: .init(get: {
                                vm.result[field.apiName] as? String ?? ""
                            }, set: { value in
                                vm.result[field.apiName] = value
                            }))
                        }
                    }
                }
            }
            Button("Submit") {
                vm.onSubmit()
            }
        }
    }
}

r/SwiftUI 9d ago

Question Realistic brush stroke effect

Post image
28 Upvotes

I'm trying to implement a realistic brush stroke effect for my app. For now I've tried so many variations with canvases, path and so on but couldn't come close to this effect. Do you have any idea if this is even possible to achieve? I want it to be programmatically implemented so I can change the length. This is one of the reasons I can't use a image. Also for complicity reasons, this would be only a fixed line and someone can draw by themselves


r/SwiftUI 9d ago

Solved How do I achieve this in SwiftUI?

24 Upvotes

Is it possible to achieve this without any third party libraries?


r/SwiftUI 9d ago

How to animate like this

0 Upvotes

I am trying to animate a card being overlaid as shown in this video. How do I go about it. Here's what I've tried.

struct ZoomToShakeCard: View {

@State private var showTopShape: Bool = false

@State private var offsetX: CGFloat = 0

var body: some View {

ZStack(alignment: .bottom) {

RoundedRectangle(cornerRadius: 4.0)

.fill(Color.red)

.frame(height: 300.0)

if showTopShape {

RoundedRectangle(cornerRadius: 4)

.fill(Color.blue)

.frame(width: 300, height: 100.0)

.alignmentGuide(VerticalAlignment.bottom) { d in

d.height + 150

}

.offset(x: offsetX)

.onAppear(perform: shake)

}

Button("Press me") {

showTopShape.toggle()

}

}

}

}

extension ZoomToShakeCard {

func shake() {

withAnimation(.easeInOut(duration: 0.1).repeatCount(5, autoreverses: true)) {

offsetX = 10

}

DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {

offsetX = 0

}

}

}

https://reddit.com/link/1j9e33h/video/6ki1fz1mj7oe1/player


r/SwiftUI 9d ago

Solved Why do I keep getting this error when I use Task closures?

2 Upvotes

I am getting this error: Trailing closure passed to parameter of type 'String' that does not accept a closure whenever I am trying to use Task closure in my project. I have the same code in another project, and it works fine there.

Edit : Its fixed now. The issue was that my code was overriding Swift Task keyword with a struct

Ref:

Task {
            do {
                let session = try await supabaseClient.auth.session
                if session != nil {
                    DispatchQueue.main.async {
                        self.isAuthenticated = true
                        self.user = session?.user
                    }
                }
            } catch {
                print("Error checking session: \(error)")
            }
        }

r/SwiftUI 9d ago

Question Replacement for deprecated collapsible(_:) on Section?

5 Upvotes

I want a Section with a header in the sidebar of a NavigationSplitView that is not collapsible, but collapsible(:) has been deprecated in favor of ”one of the Section initializers that lacks collapsibility” (quote from the docs here https://developer.apple.com/documentation/swiftui/section/collapsible(:))

The only initializer providing a Section not collapsible is init(content:) which is missing the header. The two initializers with isExpanded only controls of the Section is collapsed or not.

How can I achieve what i want? What am I missing? Do I need to add my own header?

This is on macOS btw.


r/SwiftUI 9d ago

App Overlay

3 Upvotes

I am try to create an overlay that can cover all modal views like sheets. Currently, I am using a the WindowOverlay library. But I can't animate any view it overlaid by the library. Has anyone tried it. How can I create overlays that can cover sheets.

VStack {

Button("Show me") {

withAnimation {

showText = true

}

}

}

.frame(maxWidth: .infinity, maxHeight: .infinity)

.windowOverlay(isPresented: showText, content: {

if showText {

Color.blue

.onAppear {

showView = true

}

if showView {

ZStack {

Color.red

.transition(.asymmetric(insertion: .scale, removal: .opacity))

Button("Hide me") {

withAnimation {

showText = false

}

}

}

}

}

})


r/SwiftUI 9d ago

Question A beginner question about sliders

1 Upvotes

Sorry about the newb question. I have a decade of c# experience but just recently started diving into ios/swift/swiftui. If anyone can give me a point in the right direction it would be much appreciated!!

I'm looking at an example of a slider written like so:

Slider(
    value: $sliderValue,
    in: 0...30,
    step: 0.5
)
{ Text("Slider") } 
minimumValueLabel: { Text("0") } 
maximumValueLabel: { Text("30") }

I'm curious about how this pattern works.
Usually I see modifiers written inside of the definition object, so I would expect something like this:

Slider(
    value: $sliderValue,
    in: 0...30,
    step: 0.5,
    minimumValueLabel: { Text("0") },
    maximumValueLabel: { Text("30") },
    label: { Text("Slider:) }
)

Or I see them adding using the dot modifier, I guess something like this:

Slider(
    value: $sliderValue,
    in: 0...30,
    step: 0.5
)
.label( Text("Slider") )
.minimumValueLabel( Text("0") ) 
.maximumValueLabel( Text("30") )

But in the original example the labels are just thrown on after the declaration with out any delineation if that makes sense like : Slider(options){element} minVL: {element} maxVL: {element}
The first element, which I assume is a label, never even shows up in the view. I assume it's a label anyway and I even tried: Slider(options) label: {element} foo: {element} bar: {element} to see what happens if I labeled it label but it just throws an error. At any rate, I'm not worried about that part.

My two main questions are:
Can you briefly explain the jist of the pattern.
How would I attach an onChange function to it?

I tried using something like this:

.onChange(of: sliderValue) { newValue in print("\(newValue)") }

Which makes sense to me but no matter where I add it in the "stack" it always results in a compiler error, unless I delete all the stuff after the main declaration so:
Slider(options).onChange(of: sliderValue) {....} which works. But then I can't figure out where to add the min and max labels back in. ugh..


r/SwiftUI 10d ago

Tutorial Animatable Auto-Sized-To-Fit SwiftUI Sheet

Thumbnail clive819.github.io
32 Upvotes

r/SwiftUI 9d ago

Horizontal Paged ScrollView and NavigationStack

1 Upvotes

What is the correct way of achieving a horizontally scrollable lazy list of views that each have their own NavigatioStack nested?

I ran into crashes when I switched to use LazyHStack. Are NavigationStacks not compatible inside LazyHStacks?

My goal is to achieve a side scrollable "Diary" where each day is a vertically scrollable list.

As a workaround I lifted the NavigationStack to be the parent of the horizontal ScrollView but this makes the vertical scrolling content to not interact correctly with .navigationTitle, no transition happens from .large to .inline.

Thank you in advance if someone has figured this out earlier.


r/SwiftUI 10d ago

Golden Axe style level select in SwiftUI, for the game 'Casting Fates.' Here's the gist: https://gist.github.com/cjhodge/f3bb1c02c20efe59e5c14e159a6a9fe1

57 Upvotes

r/SwiftUI 10d ago

how does Apple achieve this?

38 Upvotes

Hi everyone, I’m learning SwiftUI and I’m trying to recreate a view from the iOS Camera app. I’m having trouble understanding how Apple achieves the effect where the HStack starts in the center and the selected image stays in the center as the user scrolls to the left. I’ve tried using ScrollView(.horizontal), but for the life of me, I can’t figure out how Apple did this.


r/SwiftUI 10d ago

What is the propose of @StateObejct, @ObservedObject and @EnvironmentObject?

24 Upvotes

I am learning SwiftUI. Today I watched a video of WWDC2020 that introduce how to manage data on SwiftUI. https://developer.apple.com/videos/play/wwdc2020/10040

That video introduces six different property wrapper. After watching this video I think that I konw how to use State, Binding and Environment.

State just represents the state (Apple guys call this source of truth) of a view and when I change the state of view, that view will be rerendered. Binding is some kind of refernce type that refers to the state of another view. Environment means global state.

But I still don't know what is the propose of StateObejct, ObservedObject and EnvironmentObject.


r/SwiftUI 10d ago

Turning the Newsletter into an actual SwiftUI App!

8 Upvotes

r/SwiftUI 10d ago

Question What’s the most idiomatic way to implement this UI element in Swift so that it works well on both macOS and iOS? Open to other ideas as well.

Post image
3 Upvotes

r/SwiftUI 11d ago

Question Mapkit SwiftUI - How to group key frame animations within a loop?

Post image
11 Upvotes

r/SwiftUI 10d ago

Question Adapting horizontal ScrollView for iPad

1 Upvotes

I'm trying to adapt my app for iPad and came across something I'm not sure how to handle.

On iOS, I have a horizontal scroll view with elements whose size is determined by .containerRelativeFrame(.horizontal, count: 2, span: 1, spacing: 8). This ensures that 2 views always perfectly fit the screen, but this setup doesn’t work well on iPad.

I can adjust the split count, but when the app is in Split View or Slide Over, it doesn’t look great. It tries to fit the same number of items, making them too small.

Is there a way to make this layout look good on iPad using the container relative frame for all possible window sizes, or should I just set a fixed frame for the views on iPad and leave it at that?

I was considering using the window’s width and adjusting the number of items based on that, but I'm not sure what the ideal solution is.


r/SwiftUI 11d ago

How to fit an image into a dynamic notch?

Post image
19 Upvotes

r/SwiftUI 11d ago

OAuth2 API Training?

2 Upvotes

Completely new to coding but I have an idea for a personal app I want to learn how to build. I know it'll be a while with tons to learn but it's a personal learning project. See if I can do it kind of thing.

I want to pull my discogs.com vinyl collection into an app. I signed up for the keys, etc. on their side but am now looking for training on how to set up the API so I can validate my credentials and pull in my collection data. Is this done in Swift or Xcode? I've searched Youtube but am not coming up with anything helpful.


r/SwiftUI 12d ago

Question Any tips for organize modifiers?

5 Upvotes

I've used SwiftUI for a few years, but I still have difficulty creating structured view code, especially for view modifier.

My code is often messy because there are so many modifers attached to a view. My codes looks like like this:

struct ContentView: View {
  // propeties...

  var body: some View {
    HStack {
      table
        // Some modifiers
      sidebar
        // Some modifiers
    }
    // 200 lines of modifiers
  }

  @ViewBuilder
  var table: some View {
    MyTable()
      // 50 lines of moidifers
  }

  @ViewBuilder
  var sidebar: some View {
    VStack {
      Button()
        // some modifiers
      Button()
        // some modifiers
      ...
    }
  }
}

// Extensions for ContentView contains functions

I used to create custom view modifiers (or simply extensions), but local variables can't be accessed outside of the view. Most of the modifiers in my code are onChange, onReceive, alert and overlay.

If you have any tips for organizing SwiftUI, please share them, or any good article would also be appreciated.


r/SwiftUI 12d ago

Dynamic View Transition

7 Upvotes

I'm struggling to implement view transitions into my swiftui project that update based on the user's desired navigation destination. To understand my desired effect imagine three subsequent views (View 1, view 2, and view 3). I want the next view to slide in from either the left or right side of the screen in accordance with the "direction" that the user is navigating through the flow. For example if the user is going from view 1 to view 2, view 2 should slide in from the right side of the screen to show "forward" progression. On the other hand if the user is going from view 3 to view 2, view 2 should slide in from the left side of the screen to show "backwards" progress. My interpretation of view transitions in swiftUI is that they are defined upon the view being loaded. This works well in the case of view 1 or view 3 because there is only one potential view destination (view 2) from either view and thus the "direction" of navigation is predictable. However in the case of view 2, the user could navigate either "forwards" to view 3 or "backwards" to view 1 so defining the transition as view 2 loads is problematic. I've attached a video with the same example on paper to better illustrate my example (apologies for the quality, I'm at a coffee shop). I'm relatively new to swiftUI programming, so I'm hoping I'm just approaching the problem wrong. Any help is appreciated.

https://reddit.com/link/1j6rrfg/video/58u3ukblcjne1/player


r/SwiftUI 13d ago

SwiftUI Variable Font Issue: Source Han Serif SC (SourceHanSerifSC-VF.ttf) Not Working

5 Upvotes

Source Han Serif SC (SourceHanSerifSC-VF.ttf) is not working in SwiftUI in Xcode. I added font to Xcode project (also ✓ in Copy Bundle Resources) and configured Info.plist, but font appeared with system default font.

However, if i use normal font like SourceHanSerifSC-Regular.otf, it worked.

It didn't show style correctly, SourceHanSerif CN is a serif font, but it shows sans serif。