Provide views, controls, and layout structures for declaring your app's user interface using SwiftUI.

Posts under SwiftUI tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

WidgetBundle with ControlWidget does not work on iOS 17
I'm trying to add a ControlWidget to my WidgetBundle like this: struct MyWidgets: WidgetBundle { var body: some Widget { if #available(iOSApplicationExtension 18.0, *) { LauncherControl() } MyLiveActivityWidget() HomeScreenWidget() LockScreenWidget() } This works exactly as expected on iOS 18. However on iOS 17 my app seems to have no widgets at all. The workaround described here (https://www.avanderlee.com/swiftui/variable-widgetbundle-configuration/) does not work either since WidgetBundleBuilder.buildBlock does not accept ControlWidget as an argument. What is the correct way to include a Control widget conditionally on iOS 18?
1
0
289
1w
RTL flow in SwiftUI
I have a problem in dealing with RTL language (Arabic) in SwiftUI with List and Searchable flow, also when long pressed on the search bar to prompt the options menu it is also flipped. I added the environment parameter to support right to left layout direction for the list, but when I clicks on the search bar to do the search flow the list is flipped again, Thanks in advance. var body: some View { NavigationStack { List { Section { Text("مرحبا") } } .environment(\.layoutDirection, .rightToLeft) .flipsForRightToLeftLayoutDirection(true) .navigationTitle(" جديد") .toolbar(content: { Button("اغلاق") { self.dismiss() } }) } .tint(Color.blue) .searchable(text: self.$searchText, placement: .navigationBarDrawer(displayMode: .always)) .interactiveDismissDisabled() }
1
0
111
6d
SwiftUI: View is not rendered properly
Problem: When clicking on an item, it will be (un-)completed. When it's completed then ChildView should show GroupsView. However, that's not the case. The logs are like this: init, group Fruits - items not completed false - showItems false body, group Fruits - items not completed false - showItems true init, group Fruits - items not completed false - showItems false init, group Fruits - items not completed false - showItems false import SwiftUI import SwiftData @main struct MainApp: App { var body: some Scene { WindowGroup { SomeView() } .modelContainer(appContainer) } } struct SomeView: View { @Query private var items: [AItem] var body: some View { ParentView(items: items) } } struct ParentView: View { private var groupedItems: [GroupedAItems] = [] init(items: [AItem]) { Dictionary(grouping: items) { $0.categoryName } .forEach { let groupedItems = GroupedAItems(categoryName: $0.key, items: $0.value) self.groupedItems.append(groupedItems) } } var body: some View { ScrollView { VStack(spacing: 15) { ForEach(groupedItems, id: \.self.categoryName) { groupedItems in ChildView(groupedItems) } } } } } struct ChildView: View { public var groupedItems: GroupedAItems @State private var showItems: Bool init(_ groupedItems: GroupedAItems) { self.groupedItems = groupedItems self._showItems = State(initialValue: !groupedItems.completed) print("init, group \(groupedItems.categoryName) - items not completed \(!groupedItems.completed) - showItems \(showItems)") } var body: some View { print("body, group \(groupedItems.categoryName) - items not completed \(!groupedItems.completed) - showItems \(showItems)") if showItems { return AnyView(ItemsSampleView(items: groupedItems.items, onClick: { showItems = false })) } else { return AnyView(GroupsView(groupedItems: groupedItems, onClick: { showItems = true })) } } } struct ItemsSampleView: View { public var items: [AItem] public var onClick: () -> Void private let gridColumns = [GridItem(.adaptive(minimum: CGFloat(70)))] var body: some View { VStack { Button { onClick() } label: { Image(systemName: "chevron.down") } Spacer() LazyVGrid(columns: gridColumns) { ForEach(items.sorted(by: {$0.name < $1.name})) { item in Button { item.completed.toggle() } label: { Text(item.name) } } } } } } struct GroupsView: View { public var groupedItems: GroupedAItems public var onClick: () -> Void var body: some View { VStack { Button { onClick() } label: { Image(systemName: "chevron.down") } Spacer() Text(groupedItems.categoryName) } } } @Model final class AItem: Identifiable { @Attribute(.unique) public var id: String public var name: String public var categoryName: String public var completed = false internal init(name: String, categoryName: String) { self.id = UUID().uuidString self.name = name self.categoryName = categoryName } } struct GroupedAItems { var categoryName: String var items: [AItem] var completed: Bool { items.filter { !$0.completed }.isEmpty } } @MainActor let appContainer: ModelContainer = { do { let container = try ModelContainer(for: AItem.self) // Make sure the persistent store is empty. If it's not, return the non-empty container. var itemFetchDescriptor = FetchDescriptor<AItem>() itemFetchDescriptor.fetchLimit = 1 guard try container.mainContext.fetch(itemFetchDescriptor).count == 0 else { return container } container.mainContext.insert(AItem(name: "Apple", categoryName: "Fruits")) return container } catch { fatalError("Failed to create container") } }()
1
0
107
6d
Public and Private CK sync failure, macOS mistake = add data before indexing
I have a Multiplatform app for iOS and macOS targets. I am using CloudKit with CoreData and have successfully established a private and public database. The app has successfully synced private and public data for months between macOS (dev machine), an iPhone 13 Pro and an iPad Pro 12.9inch 2nd gen. The public data also syncs perfectly to simulator instances running under other iCloud accounts. Recently I added a new entity in the public DB and here is where I seemed to have made a mistake. I entered data into the new public database via my developer UI built into the macOS app running on my MBP before I indexed the necessary fields. Side note - I find it necessary to index the following for each Entity to ensure iCloud sync works as expected on all devices... modifiedTimestamp - Queryable modifiedTimestamp - Sortable recordName - Queryable Realising my mistake, I indexed the above CKRecord fields for the new Entity. Since then, the macOS target has remained in some way "frozen" (for want of a better term). I can add new public or private records in the macOS app but they do not propagate to the public or private stores in iCloud. I have attempted many fixed, some summarised below: clean build folder from Xcode; remove all files from the folder /Users//Library/Containers/, place in recycle bin, empty recycle bin, then build and run; build and run on iPhone and iPad targets to ensure all apps are current dev version, then repeat above processes. I've read through the console logging when I build and run the macOS app many many times to see whether I can find any hint. The closest thing I can find is... BOOL _NSPersistentUIDeleteItemAtFileURL(NSURL *const __strong) Failed to stat item: file:///Users/<me>/Library/Containers/com.me.AppName/Data/Library/Saved%20Application%20State/com.me.AppName.savedState/restorecount.plist but my research on this and other forums suggests this is not relevant. Through this, the app still functions as expected on iOS devices and both private and public database additions and modifications propagate to iCloud stores and to other devices. I expect that removing the macOS app entirely from my dev machine would trigger a complete sync with all existing data. Imagine I bought a new macOS device and chose to install my app where before I had run this only on my iOS devices. My current problem suggests that I could not do this, but I know that this is not the intended behaviour. This scenario makes me think there is a setting file for my macOS app that I'm not aware of and that this impeding the sync of all existing app data back to the fresh install of the macOS app? But that is a wild guess. Running public releases (no betas) Xcode 15.4 (15F31d) macOS Sonoma 14.5 physical iOS devices running iOS 17.5.1 Any words of wisdom on how I might go about trying to solve this problem please?
1
0
141
2h
WatchOS 10.5 TabView Mem Leak Help Please
Target: WatchOS 10.5 NOTE: This is a watchOS only app Given: A single view containing NavigationSplitview, with the List in the "sidebar", a TabView in the "detail" and a TabView in a sheet attached to each tab in the "detail" view. When: Navigating between top-level list and "detail" TabView, or navigating through "detail" to "sheet" TabView Then: Memory leaks occur. If the TabView() views are replaced with List() views there are no longer memory leaks. There are no reference types involved. Everything is in Structs Code below causes the issue which can be observed in Instruments. So my question is what have I coded incorrectly to cause this issue? Or, How can I fix this? Thanks in advance. @main struct VerticalTabView_MemLeak: App { var body: some Scene { WindowGroup { ContentView() } } } struct ContentView: View { struct ParentItem: Identifiable, Hashable { var id = UUID() var name: String var children: [Item] init(_ name: String, _ children: [Item]){ self.name = name self.children = children } } struct Item: Identifiable, Hashable { var id: UUID = UUID() var name: String init(_ name: String){ self.name = name } } @State var selectedParentItem: ParentItem? @State var selectedItem: Item? var parentItems = [ ParentItem("A", [Item("one"),Item("two"),Item("three")]), ParentItem("B", [Item("four"),Item("five"),Item("six")]), ParentItem("C", [Item("seven"),Item("eight"),Item("nine")]) ] var body: some View { NavigationSplitView { List(selection: $selectedParentItem) { ForEach(parentItems, id: \.id) { parentItem in NavigationLink(value: parentItem) { HStack { Text(parentItem.name) } .padding() } } } .navigationTitle("Top Level") } detail: { if let items = selectedParentItem?.children { TabView(selection: $selectedItem) { ForEach(items, id:\.id) { item in Text(verbatim: item.name) .tag(item) .onTapGesture { selectedItem = item } } } .tabViewStyle(.verticalPage) .navigationTitle(selectedParentItem?.name ?? "") .sheet(item: $selectedItem, onDismiss: { selectedItem = nil }, content: { item in TabView { Text(item.name).foregroundStyle(.yellow) Text(item.name).foregroundStyle(.yellow) } .tabViewStyle(.verticalPage) .navigationTitle(selectedParentItem?.name ?? "") }) } } } } #Preview { ContentView() }
1
0
163
1w
SwiftUI : NavigationStack in new iOS 18 TabView pushes twice when path in parameter
Hello, With iOS 18, when NavigationStack is in new TabView, with path parameter containing current navigation state is set, the navigation destination view is pushed twice. See below with example that pushes twice on iOS 18 but is correct on iOS 17 @MainActor class NavigationModel: ObservableObject { static let shared = NavigationModel() @Published var selectedTab: String @Published var homePath: [Route] @Published var testPath: [Route] } struct ContentView: View { @StateObject private var navigationModel: NavigationModel = NavigationModel.shared var body: some View { TabView(selection: $navigationModel.selectedTab){ HomeView() .tabItem { Label("Home", systemImage: "house") } .tag("home") TestView() .tabItem { Label("Test", systemImage: "circle") } .tag("test") } } } struct HomeView: View { @StateObject private var navigationModel: NavigationModel = NavigationModel.shared var body: some View { NavigationStack(path: $navigationModel.homePath){ VStack{ Text("home") NavigationLink(value: Route.test1("test1")){ Text("Go to test1") } } .navigationDestination(for: Route.self){ route in NavigationModelBuilder.findFinalDestination(route:route) } } } } I don't what causes the issue because it works well on iOS 16 and iOS 17. I think the path is somehow reset but I don't why (maybe by the TabView ?) Note that the bug only occurs with TabView. Don't really know if it is a TabView bug or if it is on my side. I filed a feedback with sample project FB14312064
6
6
428
3d
Unable to display contextMenu
This is a visionOS App. I added contextMenu under a combination view, but when I pressed the view for a long time, there was no response. I tried to use this contextMenu in other views, which can be used normally, so I think there is something wrong with this combination view, but I don't know what the problem is. I hope you can remind me. Thank you! Views with problems: struct NAMEView: View { @StateObject private var placeStore = PlaceStore() var body: some View { ZStack { Group { HStack(spacing: 2) { Image(systemName: "mappin.circle.fill") .font(.system(size: 50)) .symbolRenderingMode(.multicolor) .accessibilityLabel("your location") .accessibilityAddTraits([.isHeader]) .padding(.leading, 5.5) VStack { Text("\(placeStore.locationName)") .font(.title3) .accessibilityLabel(placeStore.locationName) Text("You are here in App") .font(.system(size: 13)) .foregroundColor(.secondary) .accessibilityLabel("You are here in App") } .hoverEffect { effect, isActive, _ in effect.opacity(isActive ? 1 : 0) } .padding() } } .onAppear { placeStore.updateLocationName() } .glassBackgroundEffect() .hoverEffect { effect, isActive, proxy in effect.clipShape(.capsule.size( width: isActive ? proxy.size.width : proxy.size.height, height: proxy.size.height, anchor: .leading )) .scaleEffect(isActive ? 1.05 : 1.0) } } } }
1
0
184
1w
MusicKit iOS17.5 and iOS18
Good morning, I'm trying to use MusicKit functionalities in order to get last played songs and put them into a local DB, to be played later. Following the guide on developer.apple.com, I created the required AppServices integration: Below is a minimal working version of what I'm doing: func requestMusicAuthorization() async { let status = await MusicAuthorization.request() switch status { case .authorized: isAuthorizedForMusicKit = true error = nil case .restricted: error = NSError(domain: "Music access is restricted", code: -10) case .notDetermined: break case .denied: error = NSError(domain: "Music access is denied", code: -10) @unknown default: break } } on the SwiftUI ContentView there's something like that: .onAppear { Task { await requestMusicAuthorization() if MusicManager.shared.isAuthorizedForMusicKit { let response = try await fetchLastSongs() do { let request = MusicRecentlyPlayedRequest<Song>() let response = try await request.response() var songs: [Song] = response.items.map { $0 } // do some CloudKit handling with songs... print("Recent songs: \(songs)") } catch { NSLog(error.localizedDescription) } } } } Everything seems to works fine, but my console log is full of garbage like that: MSVEntitlementUtilities - Process MyMusicApp PID[33633] - Group: (null) - Entitlement: com.apple.accounts.appleaccount.fullaccess - Entitled: NO - Error: (null) Attempted to register account monitor for types client is not authorized to access: {( "com.apple.account.iTunesStore" )} is there something I'm missing on? Should I ignore that and go forward with my implementation? Any help is really appreciated.
1
0
198
6d
Swift MultiDatePicker doesn't detect dates that have been saved previously and then loaded in from firebase.
Hey, currently working on my first SwiftUI app in college and would appreciate any help. I have an issue where when dates are loaded from firebase into the "selectedDates" array of my MultiDatePicker, the onChange function does not recognize dates that are already in the "selectedDates" array, instead re-adding them to the array. I.e. if I have loaded July 19th into the multidatePicker, it displays on the calendar, but clicking July 19th on the multidatepicker calendar view doesn't remove it from the "selectedDates" array. This is the code for the view: VStack { MultiDatePicker("Select dates", selection: $selectedDates) .padding() .onChange(of: selectedDates) { oldValue, newValue in saveDates(dates: selectedDates) } List(savedDates, id: \.self) { date in Text("\(date, formatter: dateFormatter)") } .listStyle(.plain) } .onAppear { loadSavedDates() } Where selectedDates is a state variable: @State var selectedDates: Set<DateComponents> = [] If nothing is on Firebase, the selection and deselection of dates happens fine, but if I am loading dates from firebase then the multidatepicker doesn't detect de-selection of dates. Here's my code for loading the dates from firebase: func loadSavedDates() { let db = Firestore.firestore() let uid = try! AuthenticationManager.shared.getAuthenticatedUser().uid print("User ID: \(uid)") print(widget.id.uuidString) db.collection("spaces") .document(spaceId) .collection("dates") .document(widget.id.uuidString)//widget.id.uuidString .getDocument {document, error in if let document = document { if let dateStrings = document.data()?[uid] as? [String] { let dateFormatter = DateFormatter() dateFormatter.dateStyle = .medium self.savedDates = dateStrings.compactMap { dateFormatter.date(from: $0) }.sorted(). let calendar = Calendar.current self.selectedDates = Set(self.savedDates.map { calendar.dateComponents([.year, .month, .day], from: $0) }). for component in selectedDates { print(component.isValidDate) } } } else { print("Document does not exist") } } As you can see, I believe I am setting the selectedDates array correctly with datecomponents. Is there a problem with my code or is there just no way to pass dates from Firebase into multidatepicker?
0
0
171
1w
Not receive onDisappear event on the first WindowGroup
Hi, I'm working on visionOS and find I can't get onDisappear event just on the first window after app launch. It comes like that: WindowGroup(id:"WindowA"){ MyView() .onDisappear(){ print("WindowA disappear") } } WindowGroup(id:"WindowB"){ MyView() .onDisappear(){ print("WindowB disappear") } } WindowGroup(id:"WindowC"){ MyView() .onDisappear(){ print("WindowC disappear") } } When the app first launch, it will open WindowA automatically And then I open WindowB and WindowC programatically. Then I tap the close button on window bar below window. If I close WindowB/WindowC, I can receive onDisappear event If I close WindowA, I can't receive onDisappear event If I reopen WindowA after it is closed and then close it again by tap the close button below window, I can receive onDisappear event Is there any logic difference for the first window on app launch? How can I get onDisappear Event for it. I'm using Xcode 16 beta 2
3
0
192
5d
TextEditor Issue with Long Text Input
I'm encountering an issue with the TextEditor in my app when users input long texts. Specifically, when entering a large amount of text with many lines, not all of the text is visible. For example, after inputting the entire story of Cinderella, adding or deleting text causes the text towards the end to become obscured and not visible. A sample project illustrating this issue is available on GitHub: https://github.com/fuziki/TextEditorManyLinesIssue I have included a video in the project file demonstrating this issue. Is there a way to resolve this issue? Platform and Development Environment. iOS: iOS 17.5.1, Xcode 15.2 (15C500b)
2
0
160
1w
SwiftData Model deletion works unstable
Hi, I believe this question belongs here instead of Stack Overflow as SwiftUI + SwiftData is too new. I am using Model Context from a static Helper class: Class Helper { static let shared = Helper() var modelContext: ModelContext? } call to insert data on the 1st screen: Helper.shared.modelContext?.insert(item) Query Model declaration on the 1st screen: @Query private var products: [ProductModel] also autoSave turned to false: .onAppear{ Helper.shared.modelContext?.autosaveEnabled = false } periodically update data via a standard Timer object: for item in products { item.price = 500 } SwiftData works just fine in this 1st screen, but when we try to delete the Model and move on to next screen, we found out memory of the previous screen Model (ProductModel) in this case is still persisted and keep increasing! Eventually causing hang in the 2nd screen. Model deletion code in onDisappear of the 1st screen: .onDisappear{ try? Helper.shared.modelContext?.delete(model: ProductModel.self) try? Helper.shared.modelContext?.save() } Any clue where we might be wrong? Thanks
1
0
120
5d
StateObject unexpectedly init twice
Environment (Simulator & Device): iOS 17.5.1 iOS 16.7 iOS 18.0 beta 3 Steps to Reproduce: Build and run On the main screen, tap “First”. Then tap “Second”. Observed Behavior: On iOS 17.5.1, the StateObject attached to DetailView is initialized twice. The expected behavior is that the StateObject should be initialized only once. On iOS 16.7, the StateObject is initialized only once, as expected. On iOS 18.0 beta 3, the StateObject is initialized only once initially. However, if you swipe down to dismiss the DetailView, the StateObject is unexpectedly initialized again. Expected Behavior: The StateObject should be initialized only once, and should not be reinitialized when dismissing the DetailView. Please investigate this issue. FB14283951 import SwiftUI class Object: ObservableObject { @Published var flag = false init() { print("object init") } } struct DetailView: View { @StateObject var object = Object() var body: some View { Text("\(object.flag)") } } struct ContentView: View { @State var showingFirst = false @State var showingSecond = false var body: some View { NavigationStack { ZStack { Button("First") { showingFirst = true } .sheet(isPresented: $showingFirst) { NavigationStack { // replace this ZStack with Form, List, issue exists. // remove this ZStack, issue gone. ZStack { Button("Second") { showingSecond = true } .sheet(isPresented: $showingSecond) { DetailView() } } } // 2nd NavigationStack } // 1st sheet } // ZStack } // 1st NavigationStack } // body } // ContentView
1
0
149
1w
SwiftUI: How to blend between UIImages without pulsating/pumping effect?
I want to smootlhy blend two or more UIImages without pulsating/pumping effect but cannot achieve this. I have created a simple example code to visualize my issue. Two UIImages with exactly the same content ("gear") are initialized. The images are then manipulated via "func resizeImage()" with: UIGraphicsBeginImageContext() defer { UIGraphicsEndImageContext() } draw(in: CGRect()) This custom draw: (in:) is important for me as in my app there is a lot of custom drawing logic. In the body I use a PhaseAnimator to animate through the different stages of my custom animation. The result is always a pulsating/pumping effect which is unwanted. If the shape of two blended UIImages is exactly the same, there should not be any noticeable difference, especially no intensity change. How to get a smooth blend without pulsating/pumping effect? Any help appreciated. import SwiftUI struct ContentView: View { @State var widgetSize: CGFloat = 128 let img1 = UIImage(systemName: "gear")! let img2 = UIImage(systemName: "gear")! func resizeImage(image: UIImage, newWidth: CGFloat) -> UIImage { let scale = newWidth / image.size.width let newHeight = image.size.height * scale UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight)) image.draw(in: CGRectMake(0, 0, newWidth, newHeight)) guard let newImage = UIGraphicsGetImageFromCurrentImageContext() else { return UIImage(systemName: "questionmark")! } UIGraphicsEndImageContext() return newImage } var body: some View { PhaseAnimator([1, 2]) { phase in // This is just for demonstration purposes // I have two or more UIImages that I want to smootlhy blend // The UIImages are created with image.draw // the result is a pulsating animation but I would expect // a smooth blend over with no noticable change when there are two // UIImages with identical content let i1 = self.resizeImage(image: img1, newWidth: widgetSize) let i2 = self.resizeImage(image: img2, newWidth: widgetSize) VStack { Image(uiImage: phase == 1 ? i1 : i2) .renderingMode(.template) .foregroundStyle(.white) .background(.black) Spacer() } } } } #Preview { ContentView() }
1
0
115
1w
Importing Data into SwiftData in the Background Using ModelActor and @Query
I have an app with fairly typical requirements - I need to insert some data (in my case from the network but could be anything) and I want to do it in the background to keep the UI responsive. I'm using SwiftData. I've created a ModelActor that does the importing and using the debugger I can confirm that the data is indeed being inserted. On the UI side, I'm using @Query and a SwiftUI List to display the data but what I am seeing is that @Query is not updating as the data is being inserted. I have to quit and re-launch the app in order for the data to appear, almost like the context running the UI isn't communicating with the context in the ModelActor. I've included a barebones sample project. To reproduce the issue, tap the 'Background Insert' button. You'll see logs that show items being inserted but the UI is not showing any data. I've tested on the just released iOS 18b3 seed (22A5307f). The sample project is here: https://hanchor.s3.amazonaws.com/misc/SwiftDataBackgroundV2.zip
2
2
231
6d
SwiftUI design elements
Hello everyone, for a personal project I'd like to reproduce a design element from Apple's saving application. I'd like to display three rectangles containing text: two horizontally aligned and one next to it. And I'd like the height of the last rectangle to be equal to the height of the two smallest. Does anyone have a solution? Please provide a sample code
4
0
248
1w
Is it possible to retrieve optional @EnvironmentObject
I'm trying to develop an iOS app with SwiftUI supporting iOS15 and above and then I encounter with this issue. I have a SwiftUI view and call this view from multiple different UI flows. So I want to provide different environment objects depending which flow it is in. I want them optional because depending which environment object I am able to retrieve, I want to modify properties of those environment objects to trigger UI updates. (expect to use "if let" check for optional binding) Inside that view, I want to retrieve those environment objects as optionals but I can't use @EnvironmentObject because is expects conforming ObservableObject protocol. I also tried to use EnvironmentKey protocol to define custom optional types but this time Xcode gives error as: "Failed to produce diagnostic for expression; please submit a bug report (https://swift.org/contributing/#reporting-bugs)" I really wonder If I am able to reach an optional environment object for iOS15. Note: I know that with Observation framework I may be able to get optional environment object but I have to update my supported iOS level beginning from iOS17 for the app which I can't do right now.
2
0
93
1w
MKMapview overlay renderding performance issue on iOS16
Hi , I have following scenario where I feel performance issue. Use-case: I have multiple Overlays(MKOverlay) rendered on MapView, and overlay needs to refresh on point Drag(MKPinAnnotation). I have custom logic to handle drag behaviour of annotation, on annotation drag I do update the overlay. As point update, I create new overlay with updated coordinate and re-render it. iT slow down the performance after few overlay added. Additional Notes: Performance was quite good on iOS16 but on iOS17, it lags the perforce on point drag. When I say it the performance, it point drag lags so it slow the overlay rendering. I am using MKMapView inside SwiftUI. I am sharing code-snippet where it re-render the overlay. Please help with issue in my code implementation. func renderSegments(mapView: MKMapView, segmentPoint: FencePointAnnotation, renderNeeded: Bool = true) { mapViewModel.updateFencePointOrder() guard let activeLayer = mapViewModel.activeLayer else { debugPrint("Invalid active layer.") return } let segments = mapViewModel.activeFence.connectedSegmentsOf(vertex: segmentPoint) // Remove existing overlay. for overlay in mapView.overlays { if let overlay = overlay as? FenceOverlay { if overlay.layerId == activeLayer.layerId { mapView.removeOverlay(overlay) } } else if let overlay = overlay as? FenceSegmentPolyline { if overlay.layerId == activeLayer.layerId { for segment in segments.values where segment.identifier == overlay.identifier { mapView.removeOverlay(overlay) } } } } // When vertex removed the no need to add segment if renderNeeded { if let segments = mapViewModel.updatedSegements(segment: segments.map({$0.key})) { let updatedSegments = mapView.updatedSegmentsWithOffset(segments: segments, layer: activeLayer) mapView.addOverlays(updatedSegments) } } }
2
1
126
6d