SwiftUI sheet never updated after first launch

I use a modal sheet whose content is updated for each call. However, when the content is marked as @State, the view body is never updated. Is anyone seeing this as well? Is a workaround available? This is the calling view: struct ContentView: View { @State var isPresented = false @State var i = 0 var body: some View { List { Button("0") { self.i = 0 self.isPresented = true } Button("1") {

Problem passing value with SwiftUI List(), ForEach(), .onTapGesture WatchOS6

I am trying to use the .onTapGesture() to call a method on the tapped view and pass some kind of ID or any other form of identifier, but i dont know how to. i have a view ListView that i create from data that i get from my array trackPreviewList: [TrackpreviewList]. The view looks like this: struct ListView: View { @ObservedObject var model: PlaybackService @State var list = PlaybackService.sharedInstance.trackPreviewList var body: some View { List { Section(heade

iOS SwiftUI how to bring up extra actions like "Embed in VStack" when interacting with code?

I am looking at this SwiftUI tutorial and it suggests I can see extra actions upon Command-Clicking the SwiftUI elements in code. In my Xcode, this jumps me to the class definition. I see there's an option in XCode 11.0 t change the Option key to show SwiftUI inspector, however, this still does not let me modify SwiftUI code elements using actions like "Embed in VStack" How can I get both inspector and extra SwiftUI actions when interacting with SwiftUI Code (not the preview)?

SwiftUI GeometryReader causes memory leak

Consider the following code: import SwiftUI class ViewModel: ObservableObject { } struct TestView: View { @ObservedObject var vm = ViewModel() var body: some View { // self.sample GeometryReader { _ in self.sample } } var sample: some View { Text("Hello, World!") } } struct Tabs : View { @State var selection: Int = 0 var body: some View { TabView(selection: $selection) { TestView().tabItem {

SwiftUI: Cancel TapGesture on parent view

I have view hierarchy in SwiftUI like ParentView { //other views ChildView().highPriorityGesture(TapGesture().onEnded { print("Tap!") }) // other views }self.gesture(tap) And I want to have parent view handle all taps on the screen in spite of cases when user taps onto ChildView. Now both closures executes. How to stop tap gesture events propagating up view hierarchy?

SwiftUI: Alignment not applied

I have a small example that U do not understand: Why is the alignment of my ZStack not applied to all of it's children? The TopView stays on top but I would expect, that every child would be on bottom right: struct ContentView: View { var body: some View { ZStack(alignment: .bottomTrailing) { VStack { TopView() Spacer() } Text("A new layer") }.padding() } } struct TopView: View { var body: some View

Swiftui How to publish changes to a single object in a object array

I have the following classes class ListItem: Identifiable { var id: UUID var name: String var description: String var isFavorite: Bool var debugDescription: String { return "Name: \(self.name) | Favorite?: \(self.isFavorite)" } public init(name: String) { self.name = name id = UUID() self.description = "Some text describing why \(self.name.lowercased()) is awesome" self.isFavorite = false } } class ListItems: Observable

SwiftUI stops updates during scrolling of List

Given a List in SwiftUI, once panning begins, updating of views in the list seems to pause until the scrolling has been stopped. Is there a way to prevent this? Consider the following code: class Model: ObservableObject, Identifiable { @Published var offset: CGFloat = 0 let id = UUID() private var timer: Timer! init() { timer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true, block: { _ in self.update() }) } func update() {

SwiftUI - make sure to publish values from the main thread (via operators like receive(on:)) on model updates

My app contains a resource heavy operation that populates an Array based on data pulled from an XML feed. I do not want this operation to lock up the main thread (and the UI when the array is given new data), so it's done in the background. let dispatchQueue = DispatchQueue(label: "concurrent.queue", qos: .utility, attributes: .concurrent) class XMLHandler: ObservableObject { let context: NSManagedObjectContext @Published var myArray: [CustomObject] = [] init(context: NSMa

Swiftui Swift: NavigationLink calling destination's init method multiple times

I have two classes SubmitPhoneView and VerifyPhoneView. For some reason, I noticed that whenever I input a digit into the textfield of SubmitPhoneView, it calls the init method of VerifyPhoneView. I want it to only be called once (when I press the continue button on SubmitPhoneView) Why would this be? Class SubmitPhoneView: import SwiftUI import Firebase struct SubmitPhoneView: View { @State private var phoneNumber: String = "" @State private var verificationID : String = "" @S

How to declare GMSMapViewDelegate on SwiftUI

I'm newbie in SwiftUI and trying to implement a solution with GoogleMapsApi with a map where user can touch the map and do things. For that, I understand delegate must be implemented, but I can't figure out how to achieve that with SwifUI. There's a lot of code samples on web, when in Swift or even Objective C, but I couldn't find any on SwifUI. Here's what I did (I'm trying to keep this code as simple as it could be): struct GoogleMapsHomeView: UIViewRepresentable { func makeUIView(cont

What is difference between GeometryReader and GeometryProxy in SwiftUI?

As per Apple, GeometryReader A container view that defines its content as a function of its own size and coordinate space. GeometryProxy: A proxy for access to the size and coordinate space (for anchor resolution) of the container view. I am trying to understand when to use GeometryReader and when to use GeometryProxy? I did google but didn't see any post coming up in results. So I am asking here so that new developers like me can use it for reference.

SWIFTUI - Picker view touch/scroll-able area is still out of frame even after using clipped()

SWIFTUI I have a picker view(wheel type) and I clipped() its frame to half width of the screen, and from the UI you can see its half but the scrollable area is still actionable outside that frame. How can I remove that outer area to not be scrollable? HStack(spacing: 0) { Picker(selection: self.$viewModel.selectedFrameworkIndex, label: Text("")) { ForEach(0 ..< viewModel.Categories.count) { Text(self.viewModel.Categories[$0]) .foregroundColor((self.colorScheme ==

Swiftui how to subscribe to a function, which observes @Published?

It is required to dynamically render messages list in a SwiftUI body block: var chatSpace: some View { List(self.viewModel.getMessages(), id: \.self) { message in message } } where view model, is the instance of the following class: class MessagesListViewModel: ObservableObject { @ObservedObject var messageService: MessageService init(messageService: MessageService) { self.messageService = messageService } func getMessages() -

Swiftui ZStack - IOS 14 beta - Zstack fly on the keyboard

In new IOS 14 beta i use ZStack to display badge on my tabs. When keyboard is appear - zstack fly on the keyboard, but it must be fixed in the bottom. IOS 13 - has nothing like this. ZStack { Circle() .foregroundColor(.red) Text("\(self.realm.ItemsAll.count)") .foregroundColor(.white) .font(Font.system(size: 11)) }.frame(width: 15, height: 15)

Delay Gestures in SwiftUI

I'm creating a complex view that contains a ScrollView with draggable elements in it. I use DragGesture() for each element to implement dragging. My Problem Whenever I touch down an element, its DragGesture will be activated immediately and the ScrollView will not be scrolled when the touch is moved. My Goal I would like to add a time delay (say 1 second) for each DragGesture, such that when the user moves his touch on an element within that time, the ScrollView will be scrolled, but when he tou

Swiftui Binding<Bool> to Binding<Bool?> in Swift

NavigationLinks selected parameeter takes in Binding but my ObservedObject has Bool variable not an Optional value. How to convert it so that selected would accept it? Code: class RegistrationFlowEnvironment: ObservableObject { @Published var done = false } the view: struct ContentView: View { @ObservedObject var regFlowEnv = RegistrationFlowEnvironment() var body: some View { NavigationView { VStack{ NavigationLink("Go to other pla

How can I prevent the view not to refresh if the parameter of ObservedObject didn't change at all in swiftui

I have a ObservedObject as model. Inside the model I have the 2 properties, 1 is use for init a view and 1 is us for display a view in FullScreen. The problem I am facing is the ViewWithPara got refreshed when the fullscreen view is display. I dont know why this happen because the parameter pass to the ViewWithPara didnt change at all but still trigger the view to refresh. Hope someone can explain to me. Thanks Step to reproduce Check the Show Button to show the full screen and close it with be

SWIFTUI tex auto animation with colors

How do I make Text auto animate with shuffling colors or using LinearGradient to animate text? Or animate borderline of text? I can animate it on tap gesture but can't figure out a way for it to auto animate, in a ForEach. .onAppear() { withAnimation(Animation .easeInOut(duration: 0.6) .repeatForever(autoreverses: true)) { print("ree: \(self.fadeInOut)") self.fadeInOut.toggle() } } .opacity(self.fadeInOut ? 0 : 1) Thanks

SwiftUI: Real device shows strange behavior with asynchronous flow, while Simulator runs perfectly

*** EDIT 23.20.20 *** Due to the strange behavior discovered after my original post, I need to completely rephrase my question. I meanwhile re-wrote large parts of my code as well. The issue: I run an asynchronous HTTP GET search query, which returns me an Array searchResults, which I store in an ObservedObject FoodDatabaseResults. struct FoodItemEditor: View { //... @ObservedObject var foodDatabaseResults = FoodDatabaseResults() @State private var activeSheet: FoodItemEditorSheets.S

How can I update the location X for offset in exact tap point for a view in SwiftUI?

I am trying to update my Rec offset with drag Gesture of this Rec, I already coded in this way that the Rec start moving itself depending on drag and follow the drag as I coded, the problem that I get with this is it get centered itself always and I can not drag Rec out of screen, my goal is coding in way that offset start working with inter location of tag and it become the source for offset, now the source is center, which I like to be dynamic and be flexible as tap on Rec. How I should code t

SwiftUi Navigation link to Same View always gets added as a subview

I'm trying to navigate to the same view with different data from a navigation link on the current view. However, I see that the new view when navigated to gets added as a child view below the first view. Like the image shown below. Is this expected? The code looks something like this. View1 is a VStack { HStack { Text("") } Divider() HStack { Text("some text") } NavigationView { VStack { NavigationLink(destination: View1(data:

Swiftui Scrollview doesn't scroll past views with an offset

To solve a much more complicated problem, I created the following simple test project: struct ContentView: View { var body: some View { ScrollView { ZStack { ForEach(0..<50) { index in Text("Test \(index)") .offset(x: 0, y: CGFloat(index * 20)) } } } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView()

How to Push View or Present View Modally in SwiftUI dynamically?

I'm learning SwiftUI and my focus at the moment is to implement a method which I'm able to implement using UIKit. I need to create a method the determines whether I should Push the View or Present modally the view based on the value of a boolean. In UIKit, my code is: var presentVC = true // boolean that determines whether VC will be presented or pushed let vc = ViewController() //Your VC that will be pushed or presented if (presentVC == true) { self.presentViewController(vc, animated: tr

Swiftui The renderer function in SCNSceneRendererDelegate is only called by input, not automatically

I am aware that this question has been discussed many times before. Nevertheless, it is unclear to me how the whole thing has to be implemented in SwiftUI. Currently: After an input (for example moving the camera) the renderer function is called correctly. Goal: The renderer function should also be called without needing input. Setup: struct ContentView: View { @ObservedObject var gameData : GameViewModel var body: some View { SceneView( scene: gameData.scene,

Questioning the dynamicity of Spacers in SwiftUI

I have heard from multiple places that spacers are meant to be dynamic/relative to different screen sizes. I have been using them as an important piece to my layout but they have let me down. Can someone show me if I'm using them incorrectly? Here is an example of a rectangle with an HStack of squares across it. Since the rectangle starts out big and I also need to push it down to the screen I use a lot of spacers(which seem unnecessary). I have tried using padding but it doesn't push it down as

How to iterate over all segments/points of a Path of a Shape in SwiftUI?

Let's say I have a Shape: struct Triangle: Shape { func path(in rect: CGRect) -> Path { var path = Path() path.move(to: CGPoint(x: rect.midX, y: rect.minY)) path.addLine(to: CGPoint(x: rect.minX, y: rect.maxY)) path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY)) path.addLine(to: CGPoint(x: rect.midX, y: rect.minY)) return path } } How can I get the Path of this Shape and iterate over all points of this path? This rectangle is just a

Swiftui I'm trying to use a a semitransparent overlay with a masked out area to focus the user's attention, but it won't work despite trying several solutions

I'm trying to make an inverted mask in my application and grey out a surrounding area to focus the user's attention to the center. That is, I want to use the path to mask out the inside area and thus grey out the area outside the path (you'll hopefully see what i mean in the code). I've tried finding this answer on my own and tried out several suggestions found here on SO (it's how i found the "oeFill" solution below), but so far the solutions I've tried hasn't worked, it's always inve

SwiftUI: Distribute views within container evenly?

Let's say I have a ZStack with an indeterminate/flexible width. There are four views within this ZStack. How would I distribute the views evenly... as if I were fanning out a deck of cards (with each card overlapping the next), like this: I can accomplish this effect with .offset(x: ?) if I know the width of the container: ZStack { Text("One") .frame(width: 99, height: 150, alignment: .topLeading) .background(Color.blue) .offset(x: -99) Text("Two&q

SwiftUI: How to show some toolbar buttons only for iPhone

I have a set of toolbar buttons that should be presented only if the device is iPhone (not iPad). The following code fails with this error: Closure containing control flow statement cannot be used with result builder 'ToolbarContentBuilder' I do understand why it fails, but I am not be able to come up with a solution, which achieves what I need. import SwiftUI struct ContentView: View { var body: some View { NavigationView { List { NavigationLink(

Swiftui How to declare functions in Swift?

I want to know how to declare and call functions using SwiftUI, I have written the following code, what is wrong with it? struct ContentView: View { var body: some View { printHello() } func printHello() { print("Hello from function!") } }

SwiftUI Optional TextField

Can SwiftUI Text Fields work with optional Bindings? Currently this code: struct SOTestView : View { @State var test: String? = "Test" var body: some View { TextField($test) } } produces the following error: Cannot convert value of type 'Binding< String?>' to expected argument type 'Binding< String>' Is there any way around this? Using Optionals in data models is a very common pattern - in fact it's the default in Core Data so it seems strange that SwiftUI wou

SwiftUI TabView in NavigationView hierarchical stack has extra space at the top of the screen

I have a flow of user registration. Where Welcome screen wrapped in NavigationView and then after several screens NavigationLink opens TabView. As I understand, as a result, TabView is in this navigation stack and has an extra space at the top of the screen. How to avoid this situation? I've tried this solution: https://stackoverflow.com/a/57332701/9325884 But it works only if you have one aka Login screen. So, I'm looking for a solution how to switch between two Navigation stacks. TIA

Swiftui Any way to share global variables between Struct & Class? @Environment doesn't work

Scenario: I have a tabbed-based application with parallel network routines of similar function. Each has has its own network error handler which sends out a @Published alert flag to notify the calling host's alert operator to display the respective alert. In this case, I have a 'No Internet' alert. Problem: Having only one (1) network error routine is okay... but having multiple-network routines creates multiple network errors which either: Requires multiple .alert operators (one per

SwiftUI NavigationBarItem Hover Effect on iPadOS

When using UIKit, the UIBarButtonItems automatically get support for the highlight hover effect when using a pointer in iOS 13.4+. After updating some views to use SwiftUI, the equivalent NavigationBarItem modifiers do not have a highlight hover effect. Is this a bug, not supported, or implemented in a different way?

Is there a way to create a new session of WKExtendedRuntimeSession in SwiftUI?

I've created a simple countdown timer in watchOS. When you press start the timer starts and session.start is declared as well. Everything works fine in the background. Then when it stops either by the button or by the timer the session will invalidate. By the way that I'm reading the documentation here It states, "you can only schedule one session at a time; if you need to reschedule a session, invalidate the current session, and schedule a new one." So my question is, how do I create

Swiftui How Can I Handle Tap Gesture on Widget?

I'm writing a widget with WidgetKit and I want to make the widget's content is clickable. For example, if users click to standings, I want to open the standings tab when the app becomes active. I tried to use notification between the app and widget but the tap gesture is not working, I added print inside of the tap gesture but it did not appear in the console. Also, I added the same app group to both of them. WidgetView: struct LargeWidget : View { @State var standings : [StandingsTabl

Swiftui SwifUI iOS 14 Picker Binding

SwiftUI Pickers appear not to work in iOS 14 as they used to. The lower one works perfectly, while the first one produces this error: "displayModeButtonItem is internally managed and not exposed for DoubleColumn style. Returning an empty, disconnected UIBarButtonItem to fulfill the non-null contract." Is there anything I am missing? I don't know how to get the upper version to work again? It does work if I change the picker style to the Wheel, however I prefer to use the "DefaultP

What is the SwiftUI sheet view equivalent in UIKit?

SwiftUI can easily present a sheet view on top of the existing review when a condition is met (see screen record below). What is the sheet component equivalent in UIKit? Tried to Google a result and it looks like there is a sheet related view called UIActionSheet, but that does not seem like the right UI control. REFERENCE Example of how to achieve the same behavior with UIKit. iOS 14 navigation bar title is not displayed in UINavigationController created programmatically

Swiftui onChange not firing when attached to a Picker

I have a 3-part picker, and I'm trying to make the values of one Picker to be based on the value of another. Specifically adding/removing the s on the end of "Days","Weeks",etc. I have read a similar post (here) on this type of situation, but the proposed Apple solution for IOS 14+ deployments is not working. Given that the other question focuses primarily on pre-14 solutions, I thought starting a new question would be more helpful. Can anyone shed any light on why the .on

Customize Mapbox style with layers in SwiftUI

I have an issue to customize a Mapbox view's style, like for instance adding some information on the map if a switch is switched on. Not sure if it's important, but the layers I need to add are MGLSymbolStyleLayer and MGLLineStyleLayer. Let's start with code for the main view containing a switch representing a state used to customize the map's style, and an UIViewRepresentable for the Mapbox view. struct Test_MapBox: View { @State private var styleURL: URL = MGLStyle.outdoorsStyleURL @St

How do I set a view's background to the gray'ish one in SwiftUI?

I noticed that whenever I create a view it automatically gets a white background color. If you insert a list however, no matter the size, the entire view seems to get a sort of grey background, which looks better to me than a white background. I'm wondering how I can get my background to look like this (without using a list, or an invisible dummy list maybe)? I've already tried getting the color code but that just gives me a dark grey background. I tried adjusting the opacity but it just isn't t

How to save that my button has already been tapped in SwiftUI

I have the following code that, when tapped it will add the number of likes to a post, it will only allow the user to tap it once, works well but when I reload the app I can like it again, been trying to workout the best way to save that it has been tapped already. I have added the button state as false: @State var buttonTapped = false Button(action: { self.buttonTapped.to

SwiftUI onDrop not called?

SwiftUI's drop API is only fired under certain conditions? Try dragging the "Drag Me" block over the others. For some reason, a TextEditor needs to satisfy 2 conditions before it's "superview" can detect the drop? have a background disabled struct ContentView: View { @StateObject fileprivate var viewModel = ViewModel() @State private var s1 = "Nope" @State private var s2 = "Nope" @State private var s3 = "Nope" @Sta

How can I change layout of apple ColorPicker from Circle to Square in SwiftUI?

The default button style of ColorPicker is a circle as bellow. I want to change the style of the circle button to Rectangle. But seems no API can change it style. So I put a Rectangle over it , and set it allowsHitTesting to false to transport click event to ColorPicker. struct ColorPickerView: View { @State private var colorValue = Color.orange var body: some View { ZStack() { ColorPicker("", selection: $colorValue) .labelsHidden()

How to manage Scrollview Height according to textview content Swiftui

I am trying to manage scrollview height according to textview content height with other view. Code: struct TextviewWithScrollview: View { @State private var textStyle = UIFont.TextStyle.body @State private var textForTextView = "fdgfhjdsgfdhsgfdsfg dsfg dsfgdsfh fh sf hdsjklf dhsjkfhsdjkfdhsjkfadhsfkds fdshfjkldsh fjkldsh fdshfdshfdsfhsfdsfh sf ewf g iuf herjkdsjkjvdhsvdshvdsv dshv ds vads vds hvsdvjkds vds hviuds vhv disu ghdisuv g" var body: some View { ZStack {

  1    2   3   4   5   6  ... 下一页 最后一页 共 15 页