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

Typography on Apple Watch Live Activity
I'm not quite sure whether this post belongs in a Design forum or here, but with iOS 18 Developer Beta 1 and watchOS 11 Developer Beta 1, when a Live Activity is displayed on an Apple Watch, the system font used is SF Pro rather than SF Compact. I would expect that the design guidance would be to stick with SF Compact while on watchOS, and I would expect that the system font, when displayed on the Apple Watch using .supplementalActivityFamilies([.small]), would appear as SF Compact. To ensure that SF Compact appears on my Live Activity when viewed on Apple Watch, I can set a custom font for use with the small supplemental family, but this seems really clunky; is there any other guidance here?
0
0
256
Jun ’24
Membership expired, no where to renew it?
I see the following notification in my apple developer account dashboard: Your Apple Developer Program membership wasn’t renewed successfully. You can still renew your membership within the next 27 days and your apps will remain available on the App Store during this time. Open the Apple Developer app on your iPhone, iPad, or Mac. Sign in to your account, tap/click Renew, and follow the prompts when I open the developer app, sign in, there is nowhere to renew it. I have an app on the appstore with quite a few users wich is depending on my app and I worry they will not get access to it if am not able to renew my membership I appreciate any help I can get
1
0
289
Jun ’24
Xcode previews fail with JIT error
== PREVIEW UPDATE ERROR: JITError ================================== | NoBuiltTargetDescriptionCouldBeFound | | translationUnit: PreviewTranslationUnit(moduleNamePrefix: "Previews_EmptyFeedRow", sourceIdentifier: file:///Users/bryananderson/Developer/JournalApp/JournalApp/Interface/Feed/EmptyFeedRow.swift -> EmptyFeedRow.swift, parseTree: ParseTree(version: 727, statements: 3, providers: 1), update: nil, changesContextMemoizer: PreviewsPipeline.PreviewTranslationUnit.(unknown context at $34b4b9c4c).ChangesContextMemoizer(parseTree: ParseTree(version: 727, statements: 3, providers: 1), sourceIdentifier: file:///Users/bryananderson/Developer/JournalApp/JournalApp/Interface/Feed/EmptyFeedRow.swift -> EmptyFeedRow.swift, cachedValue: os.OSAllocatedUnfairLock<Swift.Optional<PreviewsModel.ParseTree.PreviewChangesContext>>(__lock: Swift.ManagedBuffer<Swift.Optional<PreviewsModel.ParseTree.PreviewChangesContext>, __C.os_unfair_lock_s>)), registryDeclarationMemoizer: PreviewsPipeline.PreviewTranslationUnit.(unknown context at $34b4b9bec).RegistryDeclarationMemoizer) | | builtTargetDescriptions: | == VERSION INFO: Tools: 16A5171c OS: 24A5264n PID: 906 Model: MacBook Pro Arch: arm64e == ENVIRONMENT: openFiles = [ /Users/bryananderson/Developer/JournalApp/JournalApp/Interface/Feed/EmptyFeedRow.swift ] wantsNewBuildSystem = true newBuildSystemAvailable = true activeScheme = JournalApp activeRunDestination = iPhone 15 Pro variant iphonesimulator arm64 workspaceArena = [x] buildArena = [x] buildableEntries = [ Remember.app ] runMode = JIT Executor == SELECTED RUN DESTINATION: name = iPhone 15 Pro eligible = true sdk = Optional(<DVTSDK:0x13870da30:'iphonesimulator18.0':Simulator - iOS 18.0:<DVTFilePath:0x600001e8c700:'/Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator18.0.sdk'>>) variant = Optional("iphonesimulator") device = Optional(<DVTiPhoneSimulator: 0x32f00d290> { SimDevice: iPhone 15 Pro (CF3C85BC-F559-4437-9072-7F30153B399B, iOS 18.0, Booted) PairedSim: <DVTiPhoneSimulator: 0x33733d150> { SimDevice: Apple Watch Series 9 (45mm) (627CE93E-EB02-4200-BE40-3DCB5C91DB44, watchOS 11.0, Shutdown) } }) == SELECTED RUN DESTINATION: Simulator - iOS 18.0 | iphonesimulator | arm64 | iPhone 15 Pro | Apple Watch Series 9 (45mm) jit enabled: true fallback to dynamic replacement: false
7
3
382
1w
List Rows Can Be Moved While Not Editing
Hi, I am building a view containing a list of struct objects. I have implemented the onMove to allow the list rows to be moved together with the toolbar EditButton. This works but I have a problem as per title, even when the EditButton is not clicked, i.e., not in editing mode, I still can move the list rows by long pressing the rows. I have searched high and low for a solution but couldn't find one that works perfectly. Below is the code snippet. I am a new iOS dev and really appreciate if someone could help me. Many thanks! @AppStorage("fruits") private var fruits = Fruits.fruits var body: some View { NavigationStack { VStack { List { ForEach(fruits) { fruit in NavigationLink(destination: FruitsView(title: fruit.title)) { fruit.icon Text(fruit.title) } } .onMove { fruits.move(fromOffsets: $0, toOffset: $1) } } .environment(\.defaultMinListRowHeight, UIElementConstants.listCellHeight) } .toolbar { EditButton() } .navigationTitle("Fruits") } } struct Fruits: Identifiable, Codable { var id: UUID var title: String var iconName: String var icon: Image { Image(systemName: self.iconName) } init(id: UUID = UUID(), title: String, iconName: String) { self.id = id self.title = title self.iconName = iconName } } extension Fruits { static let fruits: [Fruits] = [ Fruits( title: "Apple", iconName: "basket.fill"), Fruits( title: "Banana", iconName: "basket.fill"), Fruits( title: "Pineapple", iconName: "basket.fill") ] }
4
1
249
3w
SwiftUI DropDelegate + Scrollview auto scroll while reshuffle the item outside of scrollview bounds
We have a feature requirement where we need to use LazyVGrid and DropDelegate. Our view hierarchy is as follows: Color.white.ignoresSafeArea() VStack(spacing: 0) { customNavigationView ScrollView(showsIndicators: true) { LazyVGrid(columns: columns, alignment: .center, spacing: 16) { ForEach(viewModel.selectedReferences, id: \.self) { item in ZStack { Rectangle() .fill(Color.yellow.opacity(0.5)) Text(item.title) } .frame (height: 120) .background(Color.white) .padding([.leading, .trailing], 4) .overlay((draggedItem?.uuid == item.uuid && changedView) ? Color.white.opacity(0.8) : Color.clear) .clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous)) .onDrag { initialIndex = viewModel.selectedReferences.firstIndex { $0 == item } draggedItem = item changedView = false return NSItemProvider(object: String(item.uuid) as NSString) } .clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous)) .onDrop(of: [UTType.text], delegate: DragRelocateDelegate(item: item, listData: $viewModel.selectedReferences, current: $draggedItem, changedView: $changedView) { endIndex in }) } } .animation(.default, value: viewModel.selectedReferences) } .frame(width:(UIScreen.main.bounds.width)) .onDrop(of: [UTType.text], delegate: DropOutsideDelegate(current: $draggedItem, changedView: $changedView)) bottomBarView } .frame(maxWidth: .infinity) } While performing a reshuffle, auto-scroll works within the bounds of the ScrollView content. However, according to the feature requirement, auto-scroll should also work when we place an uplifted view at the top or bottom of the view. STEPS TO REPRODUCE Launch the demo. Scroll to the bottom of the LazyVGrid. Pick any item using the DropDelegate. Try to place that uplifted view on the custom navigation view. Expected Result: The ScrollView should auto-scroll. Actual Result: Auto-scroll is not working.
0
0
202
Jun ’24
Data update issue when both parent and child views are @State in SwiftUI
Here is my test code import SwiftUI struct SubView1: View { @State var data: String var body: some View { Text(data) let _ = addr() } func addr() { let a = withUnsafePointer(to: data) { pointer in return"\(pointer)" } let b = withUnsafePointer(to: self) { pointer in return"\(pointer)" } print("SubView1, \(a), \(b), \(self)") } } struct SubView2: View { var data: String var body: some View { Text(data) let _ = addr() } func addr() { let a = withUnsafePointer(to: data) { pointer in return"\(pointer)" } let b = withUnsafePointer(to: self) { pointer in return"\(pointer)" } print("SubView2, \(a), \(b), \(self)") } } struct ContentView: View { @State var data: String = "a" var body: some View { let _ = print("ContentView") SubView1(data: data) SubView2(data: data) Button("change") { data = "b" print("changed") } } } Here is what is printed ContentView SubView1, 0x000000016ce791a8, 0x000000016ce79170, SubView1(_data: SwiftUI.State<Swift.String>(_value: "a", _location: Optional(SwiftUI.StoredLocation<Swift.String>))) SubView1, 0x000000016ce79260, 0x000000016ce79230, SubView2(data: "a") changed ContentView SubView1, 0x000000016ce7d548, 0x000000016ce7d510, SubView1(_data: SwiftUI.State<Swift.String>(_value: "a", _location: Optional(SwiftUI.StoredLocation<Swift.String>))) SubView1, 0x000000016ce7d600, 0x000000016ce7d5d0, SubView2(data: "b") In my understanding, @State wrapping is monitoring of variables, and when the wrapped variables change, it will trigger the update of this page. Updating the interface means recreating the body, so all subpages will be recreated. When I click the button, the data of ContentView is updated first, which leads to the update of ContentView , and then leads to the reconstruction of SubView1 and SubView2. Judging from the changed address, it is indeed rebuilt rather than reused. But the problem is that the data of ContentView has been updated to "b" at this time, and SubView2 is indeed reinitialized using "b", so why does SubView1 still use "a"? In addition, I modified another one and added a SubView1 to ContentView struct ContentView: View { @State var data: String = "a" var body: some View { let _ = print("ContentView") SubView1(data: data) SubView2(data: data) SubView1(data: data) Button("change") { data = "b" print("changed") } } } The following result was obtained ContentView SubView1, 0x000000016d9cd1a8, 0x000000016d9cd170, SubView1(_data: SwiftUI.State<Swift.String>(_value: "a", _location: Optional(SwiftUI.StoredLocation<Swift.String>))) SubView2, 0x000000016d9cd260, 0x000000016d9cd230, SubView2(data: "a") SubView1, 0x000000016d9cd1a8, 0x000000016d9cd170, SubView1(_data: SwiftUI.State<Swift.String>(_value: "a", _location: Optional(SwiftUI.StoredLocation<Swift.String>))) changed ContentView SubView1, 0x000000016d9d1548, 0x000000016d9d1510, SubView1(_data: SwiftUI.State<Swift.String>(_value: "a", _location: Optional(SwiftUI.StoredLocation<Swift.String>))) SubView2, 0x000000016d9d1600, 0x000000016d9d15d0, SubView2(data: "b") SubView1, 0x000000016d9d1548, 0x000000016d9d1510, SubView1(_data: SwiftUI.State<Swift.String>(_value: "a", _location: Optional(SwiftUI.StoredLocation<Swift.String>))) It seems that the two SubView1 are the same object?
2
0
193
Jun ’24
SharePlay Button
I learned Sharplay from the WWDC video. I understand the creation of seats, but I can't learn some of the following contents well, so I hope you can help me. The content is as follows: I have set up the seats. struct TeamSelectionTemplate: SpatialTemplate { let elements: [any SpatialTemplateElement] = [ .seat(position: .app.offsetBy(x: 0, z: 4)), .seat(position: .app.offsetBy(x: 1, z: 4)), .seat(position: .app.offsetBy(x: -1, z: 4)), .seat(position: .app.offsetBy(x: 2, z: 4)), .seat(position: .app.offsetBy(x: -2, z: 4)), ] } It was mentioned in one of my previous posts: "I hope you can give me a SharePlay Button. After pressing it, it will assign all users in Facetime to a seat with elements quantified in TeamSe lectionTemplate.", and someone replied to me and asked me to try systemCoordinator.configuration.spatialTemplatePreference = .custom (TeamSelectionTemplate()), however, Xcode error Cannot find 'systemCoordinator' in scope How to solve it? Thank you!
1
0
314
Jun ’24
SwiftUI "scaleEffect(..)" commentary
I've a SwiftUI-based app that draws into a Canvas for a complicated, dynamic rendering. Since that rendering is based on a map of the world, I transform the provided context to (±180°×±90°) longitude / latitude coordinates before stroking paths etc. Note that the necessary scaling flips the Y-axis because latitude increases up the screen. All is well until I add words to the picture. Because of the inversion of the Y-axis, the text is rendered inverted. mercatorContext.draw(Text(satellite.commonName) .font(Font(.init(.userFixedPitch, size: 4.0))) .foregroundColor(.white), at: satPoint) My solution was to draw the text via a another (un-inverted) context which corrects the words, but requires the satPoint to be flipped to place the words at the right place on the (inverted) map .. With that preamble, someone suggested I apply scaleEffect(y: -1) to the Text and avoid messing with more than one GraphicsContext. This seemed an excellent solution but it doesn't work .. context.draw(Text(.. draws a Text view but applying scaleEffect turns it into a View which context.draw can't accept. Once it's a View, I suppose I could convert it to an Image and context.draw(Image(.. instead which seems messy. I wondered about the scaleEffect function .. is it the case that it would ever actually return a view type that was different from the type it was given? Leaving my curiosity aside, what would a better way than using a second context to keep my text upright?
0
0
175
Jun ’24
SwiftUI pushWindow debug
In my case, I open an immersiveSpace and windowGroupA together. When I successfully push a new windowGroupB from windowGroupA, dismissing windowGroupB should return me to windowGroupA. However, this fails, and windowGroupA remains in the background scenePhase. I tried closing immersiveSpace, and it worked successfully. Therefore, pushWindow cannot be used when immersiveSpace is open.
1
0
188
4w
About NavigationLink Inside NavigationSplitView's Sidebar
Hello, In the code below, I want to navigate back to the SecondView when pressing the back button in the ThirdView. However, it navigates to the FirstView instead. How can I make it navigate back to the SecondView without going to the FirstView? struct FirstView: View { var body: some View { NavigationSplitView { Text("Here is the FirstView") NavigationLink("Go to SecondView") { SecondView() } } detail: { EmptyView() } } } struct SecondView: View { var body: some View { Text("Here is the SecondView") NavigationLink("Go to ThirdView") { Text("Here is the ThirdView") } } }
1
0
150
Jun ’24
How to customise text field? tvOS
I'd like to customise text fields in my application, but I don't see any options for it. When I click text field, new window opens. And there is no title or description. But there must be something that allows me to customize it, right? Apple applications contain customised text fields. This is apple's text field (after clicking on it) This is my text field (after clicking on it) Here is my code: Form { //... TextField("", text: $address) //... } And there is one more problem. After filling this TextField I click enter and it immediately opens the next TextField. I don't want this behaviour.
1
1
203
Jun ’24
@Previewable version problem iOS 18 - 17
Hi, i am currently updating my app in SwiftUI from iOS 16.4 to 18.0, i am getting in xcode these new warning @State' used inline will not work unless tagged with '@Previewable' so i fix the problem with the suggestions and add the new tag @Previewable and put the variable in the first line of the preview #Preview { @Previewable @State var enabled: Bool = true return NotificationLabel(enabled: $enabled, type: "test", icon: "star", title: "test", description: "test") } the problem is that my app is available from iOS 16.4 to iOS 18.0 and the preview gives me this error 'Previewable()' is only available in iOS 18.0 or newer but if i put a versione if at the top i get another error if #available(iOS 18.0, *){ @Previewable @State var enabled: Bool = true @Previewable' items must be at root scope in the preview block is there a way to silence the warning making a two version preview, one for iOS 18 and one for the previous versions?
1
0
388
Jun ’24
Ultra Action Button showing on screen
When I initiate WKExtendedRuntimeSession with a background mode of "Underwater Depth" I get an orange indicator showing the Action button on the screen that stays showing all the time and then animates when you press the action button. I believe this started with a recent WatchOS update, because it never happened before. Does anyone know how to hide it? Or keep it and be able to detect the Action button presses within my app (if possible)?
1
0
236
Jun ’24
Impossible to enter Chinese characters in searchable() field after token insertion
It is impossible to enter Chinese characters after tokens are inserted into .searchable text field. Input is directly converted into Pinyin alphabets without giving the user a chance to choose its corresponding Chinese character. If no view is provided in the "token" view builder of the searchable initializer, then this issue does not happen. I have filed feedback FB13957127. In the meantime, I was wondering if there are any possible workarounds? This bug essentially prevents Chinese users from using the search feature of my app. Thanks!
1
0
160
Jun ’24
Error Loading USDZ File in Vision Pro Application
Hi everyone, I'm working on a Vision Pro application and encountering an issue while trying to load a USDZ file. Here are the details: File Path: /Users/siddharthpatel/Library/Developer/CoreSimulator/Devices/31F10013-50B6-4CEF-9388-9094087FAEBF/data/Containers/Data/Application/EB260F0A-A84F-4E95-876D-08199D2A4998/Documents/hive1.usdz Code: do { try await modelEntityForCollider = ModelEntity(contentsOf: fileURL!) } catch { print("Error loading model: (error)") } Error: Thread 1: Fatal error: Failed to import entity from "/Users/siddharthpatel/Library/Developer/CoreSimulator/Devices/31F10013-50B6-4CEF-9388-9094087FAEBF/data/Containers/Data/ ... ve1.usdz" I've verified that the file path is correct and the USDZ file exists at the specified location. What could be causing this error and how can I resolve it? Thanks in advance for your help! Siddharth
2
0
221
3w
onDisappear (or similar) for macOS Settings/Preferences screen
Hi All, this question has been asked before by others, without any success so far. I'm using the following (standard) method to open the system provided settings screen for my macOS (only) app in SwiftUI. var body: some Scene { Settings { PreferencesView() } if #available(macOS 13, *) { // MenuBarExtra requires macOS 13, but SettingsLink used in here requires macOS 14 MenuBarExtra("...", image: "...") { ... // this one requires macOS 14 if #available(macOS 14, *) { SettingsLink() { Text("Settings...") } } else { Button { NSApp.sendAction(Selector(("showSettingsWindow:")), to: nil, from: nil) } label: { Image(systemName: "gear") } } } } } I want to know when the settings window closes. onDisappear does not work as the settings window is not really closed, but hidden. So the view stays active. All other hacks I have found neither work. Does anyone have any idea?
1
0
208
Jun ’24
Autofill multiply SecureFields issue in SwiftUI view
Hello forums, I have a problem with Autofill multiply SecureFields. I created a SwiftUI view with 2 SecureFields, createPassword and confirmPassword. Does not matter how I change the textContentType, AutoFill will only fill the first SecureField. For testing, I set the first SecureField textContentType to .none / .userName/ .email, and second SecureField sets to .newPassword, but AutoFill still fills password in first SecureField. As I know Apple advises to put both SecureField textContentType to .newPassword but it seems only working in UIKit: Enabling Password AutoFill on a text input view struct ContentView: View { @State private var createPassword = "" @State private var confirmPassword = "" var body: some View { VStack { SecureField("Password", text: $createPassword) .textContentType(.newPassword) SecureField("Password confirmation", text: $confirmPassword) .textContentType(.newPassword) } .padding() } } Thank you!
0
0
229
Jun ’24