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

SwiftUI Documentation

Post

Replies

Boosts

Views

Activity

Discovered a bug where Alert button colors are changed by the tint modifier.
I used .tint(.yellow) to change the default back button color. However, I noticed that the color of the alert button text, except for .destructive, also changed. Is this a bug or Apple’s intended behavior? this occurs in iOS 18.1 and 18.1.1 Below is my code: // App struct TintTestApp: App { var body: some Scene { WindowGroup { MainView() .tint(.yellow) } } } // MainView var mainContent: some View { Text("Next") .foregroundStyle(.white) .onTapGesture { isShowingAlert = true } .alert("Go Next View", isPresented: $isShowingAlert) { Button("ok", role: .destructive) { isNextButtonTapped = true } Button("cancel", role: .cancel) { } } } thank you!
0
0
25
9h
Since iOS 18.1, the color of Alert buttons has been affected by the tint modifier.
I used .tint(.yellow) to change the default back button color. However, I noticed that the color of the alert button text, except for .destructive, also changed. Is this a bug or Apple’s intended behavior? Thank you! Below is my code: // App struct tintTestApp: App { var body: some Scene { WindowGroup { MainView() .tint(.yellow) } } // MainView var mainContent: some View { Text("Next") .foregroundStyle(.white) .onTapGesture { isShowingAlert = true } .alert("Go Next View", isPresented: $isShowingAlert) { Button("ok", role: .destructive) { isNextButtonTapped = true } Button("cancel", role: .cancel){} } }
1
0
16
10h
Customizing Tables in SwiftUI
Hi, How to customize tables in SwiftUI its color background for example, the background modifier doesn't work ? how to change separator lines ? rows background colors ? give header row different colors to its text and background color ? Kind Regards
1
0
48
10h
Macos 15.2 beta 4 App Crash
I have a SwiftUI based program that has compiled and run consistently on previous macos versions. After upgrading to 15.2 beta 4 to address a known issue with TabView in 15.1.1, my app is now entering a severe hang and crashing with: "The window has been marked as needing another Update Contraints in Window pass, but it has already had more Update Constraints in Window passes than there are views in the window. .<SwiftUI.AppKitWindow: 0x11d82a800> 0x87 (2071) {{44,0},{1468,883}} en" Is there a known bug that could be causing this crash or known change in the underlying layout model?
0
0
66
14h
Horizontal window/map on visionOS
Hi, would anyone be so kind and try to guide me, which technologies, Kits, APIs, approaches etc. are useful for creating a horizontal window with map (preferrably MapKit) on visionOS using SwiftUI? I was hoping to achieve scenario: User can walk around and interact with horizontal map window and also interact with (3D) pins on the map. Similar thing was done by SAP in their "SAP Analytics Cloud" app (second image from top). Since I am complete beginner in this area, I was looking for a clean, simple solution. I need to know, if AR/RealityKit is necessary or is this achievable only using native SwiftUI? I tried using just Map() with .rotation3DEffect() which actually makes the map horizontal, but gestures on the map are out of sync and I really dont know, if this approach is valid or complete rubbish. Any feedback appreciated.
0
0
54
16h
sourceImageURL in imagePlaygroundSheet isn't optional
I can't shake the "I don't think I did this correctly" feeling about a change I'm making for Image Playground support. When you create an image via an Image Playground sheet it returns a URL pointing to where the image is temporarily stored. Just like the Image Playground app I want the user to be able to decide to edit that image more. The Image Playground sheet lets you pass in a source URL for an image to start with, which is perfect because I could pass in the URL of that temp image. But the URL is NOT optional. So what do I populate it with when the user is starting from scratch? A friendly AI told me to use URL(string: "")! but that crashes when it gets forced unwrapped. URL(string: "about:blank")! seems to work in that it is ignored (and doesn't crash) when I have the user create the initial image (that shouldn't have a source image). This feels super clunky to me. Am I overlooking something?
0
0
57
19h
Most idiotic problem with assign value to value?
Why assigning function.formula = formula does not change function.formula to formula in one go? It's always late one change behind. struct CustomFunction has defined .formula as @MainActor. I feel stupid. There is a part of code: struct CustomFormulaView: View { @Binding var function: CustomFunction @State var testFormula: String = "" @EnvironmentObject var manager: Manager .... .onChange(of: testFormula) { debugPrint("change of test formula: \(testFormula)") switch function.checkFormula(testFormula, on: manager.finalSize) { case .success(let formula): debugPrint("before Change: \(function.formula)") function.formula = formula // Nothing happens debugPrint("Test formula changed: \(testFormula)") debugPrint("set to success: \(formula)") debugPrint("what inside function? \(function.formula)") Task { //Generate Image testImage = await function.image( size: testImageSize), simulate: manager.finalSize) debugPrint("test image updated for: \(function.formula)") } .... and it produces this output when changed from 0.5 to 1.0 Debug: change of test formula: 1.0 Debug: before Change: 0.5 Debug: Test formula changed: 1.0 Debug: set to success: 1.0 Debug: what inside function? 0.5 Debug: test image updated for: 0.5 0.5 is an old value, function.formula should be 1.0 WT??
3
0
101
1d
Share sheet configuration
I'm trying to configure the share sheet. My project uses techniques from the Apple Sample project called CoreDataCloudKitShare which is found here: https://developer.apple.com/documentation/coredata/sharing_core_data_objects_between_icloud_users# In this sample code there's a "PersistenceController" which is an NSPersistentCloudKitContainer. In the "PersistenceController+SharingUtilities" file there are some extensions, and one of them is this: func configure(share: CKShare, with photo: Photo? = nil) { share[CKShare.SystemFieldKey.title] = "A cool photo" } This text "A cool photo" seems to be the only bespoke configuration of the share sheet within this project. I want to have more options to control the share sheet, does anyone know how this might be achieved? Thank you!
0
0
42
1d
In SwiftUI in iOS 18.1, `SectionedFetchRequest` is not refreshed when changes are done to the fetched entity's attributes.
Hi, This issue started with iOS 18, in iOS 17 it worked correctly. I think there was a change in SectionedFetchRequest so maybe I missed it but it did work in iOS 17. I have a List that uses SectionedFetchRequest to show entries from CoreData. The setup is like this: struct ManageBooksView: View { @SectionedFetchRequest<Int16, MyBooks>( sectionIdentifier: \.groupType, sortDescriptors: [SortDescriptor(\.groupType), SortDescriptor(\.name)] ) private var books: SectionedFetchResults<Int16, MyBooks> var body: some View { NavigationStack { List { ForEach(books) { section in Section(header: Text(section.id)) { ForEach(section) { book in NavigationLink { EditView(book: book) } label: { Text(book.name) } } } } } .listStyle(.insetGrouped) } } } struct EditView: View { private var book: MyBooks init(book: MyBooks) { print("Init hit") self.book = book } } Test 1: So now when I change name of the Book entity inside the EditView and do save on the view context and go back, the custom EditView is correctly hit again. Test 2: If I do the same changes on a different attribute of the Book entity the custom init of EditView is not hit and it is stuck with the initial result from SectionedFetchResults. I also noticed that if I remove SortDescriptor(\.name) from the sortDescriptors and do Test 1, it not longer works even for name, so it looks like the only "observed" change is on the attributes inside sortDescriptors. Any suggestions will be helpful, thank you.
1
0
79
1d
AVSpeechUtterance problem
I see this error in the debugger: #FactoryInstall Unable to query results, error: 5 IPCAUClient.cpp:129 IPCAUClient: bundle display name is nil Error in destroying pipe Error Domain=NSCocoaErrorDomain Code=4099 "The connection from pid 5476 on anonymousListener or serviceListener was invalidated from this process." UserInfo={NSDebugDescription=The connection from pid 5476 on anonymousListener or serviceListener was invalidated from this process.} on this function: func speakItem() { let utterance = AVSpeechUtterance(string: item.toString()) utterance.voice = AVSpeechSynthesisVoice(language: "en-GB") try? AVAudioSession.sharedInstance().setCategory(.playback) utterance.rate = 0.3 let synthesizer = AVSpeechSynthesizer() synthesizer.speak(utterance) } When running without the debugger, it will (usually) speak once, then it won't speak unless I tap the button that calls this function many times. I know AVSpeech has problems that Apple is long aware of, but I'm wondering if anyone has a work around. I was thinking there might be a way to call the destructor for AVSpeechUtterance and generate a new object each time speech is needed, but utterance.deinit() shows: "Deinitializers cannot be accessed"
0
0
68
1d
I am learning swift ui by mimicing stickies but i am facing richtexteditor problem
I am learning swift ui by mimicing stickies but i am having issue with richtextui Error ViewBridge to RemoteViewService Terminated: Error Domain=com.apple.ViewBridge Code=18 "(null)" UserInfo={com.apple.ViewBridge.error.hint=this process disconnected remote view controller -- benign unless unexpected, com.apple.ViewBridge.error.description=NSViewBridgeErrorCanceled} Why it is connecting to remote service when i develop it in local for mac UI error is this. I type cursor moves and no text displayed. changed color to everything some code import SwiftUI import AppKit struct RichTextEditor: NSViewRepresentable { @Binding var attributedText: NSAttributedString var isEditable: Bool = true var textColor: NSColor = .black var backgroundColor: NSColor = .white var font: NSFont = NSFont.systemFont(ofSize: 14) I only started swift ui 2 day ago. Bought mac mini 4 3 day ago to develop ios app but learning mac app first to get experience with mac environment Who can help Contact me via discord alexk3434 I need mac developer friends.
1
0
78
1d
What's the best way to support Genmoji with SwiftUI?
I want to support Genmoji input in my SwiftUI TextField or TextEditor, but looking around, it seems there's no SwiftUI only way to do it? If none, it's kind of disappointing that they're saying SwiftUI is the path forward, but not updating it with support for new technologies. Going back, does this mean we can only support Genmoji through UITextField and UIViewRepresentable? or there more direct options? Btw, I'm also using SwiftData for storage.
0
0
94
2d
SwiftData: Default value for added property
Let's say I have a model like this: @Model final class DataModel { var firstProperty: String = "" } Later on I create a new property as such: @Model final class DataModel { enum DataEnum { case dataCase } var firstProperty: String = "" var secondProperty: DataEnum? = .dataCase } My expectation is for the data that is already stored, the secondProperty would be added with a default value of .dataCase. However, it's being set to nil instead. I could have sworn it would set to the default value given to it. Has that changed, or has it always been this way? Does this require a migration plan?
0
0
92
2d
SwiftUI DatePicker size not configurable
Hey guys, I'm totally new to Swift programming and I'm setting up a view for registering users. I use a VStack to organize the TextFields as well as a DatePicker, but the last one seems to be very rebellious. Here's my code: VStack { TextField("E-Mailadresse", text: $mail) .frame(height: 30) .textFieldStyle(.roundedBorder) .multilineTextAlignment(.center) .focused($hasFocus, equals: .mail) .onKeyPress(.tab, action: {hasFocus = .password; return .handled}) SecureField("Passwort", text: $password) .frame(height: 30) .textFieldStyle(.roundedBorder) .multilineTextAlignment(.center) .focused($hasFocus, equals: .password) .onKeyPress(.tab, action: {hasFocus = .name; return .handled}) TextField("Name", text: $name) .frame(height: 30) .textFieldStyle(.roundedBorder) .multilineTextAlignment(.center) .focused($hasFocus, equals: .name) .onKeyPress(.tab, action: {hasFocus = .prename; return .handled}) TextField("Vorname", text: $prename) .frame(height: 30) .textFieldStyle(.roundedBorder) .multilineTextAlignment(.center) .focused($hasFocus, equals: .prename) .onKeyPress(.tab, action: {hasFocus = .birthday; return .handled}) DatePicker("Geb.:", selection: $birthday, displayedComponents: [.date]) .datePickerStyle(.wheel) .clipped() //.focused($hasFocus, equals: .birthday) Button("Registrieren") {self.register()} .padding(.top, 20) .keyboardShortcut(.defaultAction) } .frame(width: 375) } And this is how it looks like: As you can see, neither is the DatePicker centered correctly (it's more left located) nor is it clipped (reduced). I also tried adding a .frame() to itself, then I was ably to reduce it to the preferred height, but I can' reduce its width and as a result of this, I can also not write a full label like "Date of Birth" or something, because the wheel of the DatePicker always overlays it... Is that a kind of misbehavior or am I missing something? Thank you very much in anticipation for your feedback! Kind regards Kevin
1
0
96
2d
Management of multiple root views in SwiftUI
Hey guys, I'm totally unexperienced in Swift coding and I'm doing my first steps using Swift Playgrounds on my macOS as well as on my iPadOS. I'm setting up a simple App that can be divided in 4 main categories (Splash, Authentication, Content, Setup). Each category (except the Splash as the short intro when running the app) can have a NavigationStack (e. g. switching between login view, register view, forgott password view in authentication). So I thought about having a root view for each of them. My google research gave me lots of ways and hints but it's not clear at all for me if I should and how I should do this. I often read about a RootViewController but I guess that's UIKit stuff and nothing for SwiftUI. Then I read about delegates and such. Then, I read an article that exactly fits my goals and I just liked to get your opinion what you think about this way to solve my plan: First of all, I define a separate class for a appRootManager: final class appRootManager: ObservableObject { enum eRootViews { case Splash, Authentification, Content, Setup } @Published var currentRoot: eRootViews = .Splash } The main app file looks like this: @main struct MyApp: App { @StateObject private var oRootManager = appRootManager() var body: some Scene { WindowGroup() { Group { switch oRootManager.currentRoot { case .Splash: viewSplash() case .Authentification: viewLogin() case .Content: viewContent() case .Setup: viewSetup() } } .environmentObject(oRootManager) .modelContainer(for: [Account.self]) } } } In each of the for root view files (e. g. Splash view) I make the appRootManager addressable and switch the root view by updating the enum value, like for example: struct viewSplash: View { @EnvironmentObject private var oRootManager: appRootManager var body: some View { ZStack { Color.blue .ignoresSafeArea() Text("Hello World") .font(.title) .fontWeight(.semibold) .foregroundColor(.white) } .onAppear() { DispatchQueue.main.asyncAfter(deadline: .now() + 3) { withAnimation(.spring()) {oRootManager.currentRoot = .Authentification} } } } } It works fine and does exactly what I like to have (when I run the app out of Swift Playgrounds). I'm just wondering why it does not work in the App Preview in Swift Playgrounds and this is why I'd like to have your opinion to the way I solve my plan. I'm very happy for any feedback. Thanks a lot in anticipation! Kind regards Kevin
1
0
94
2d
Problem with audio files in Swift
Hi guys, I've been this app for quite a while and I wanted to add audio to it but I've encountered a strange bug. Whenever I try to play the audio from the testing device, it prints out that the audio file cannot be found. I've checked multiple times the names and the code and I get no errors there whatsoever. I have no idea what might be causing this. Here's a part of the code: `import SwiftUI import AVFoundation struct Card: Identifiable { let id = UUID() let heading: String let description: String let imageName: String let detailDescription: String let sonification: String } struct ExplorepageUI: View { @State private var selectedCard: Card? @State private var showMore = false @State private var currentIndex = 0 @State private var currentCards: [Card] = [] let galaxies = [ Card(heading: "The Mice Galaxies", description: "They’re located about 300 million light-years away in the constellation Coma Berenices.", imageName: "TheMiceGalaxiesHubble", detailDescription:""" Their name refers to the long tails produced by tidal action, the relative difference between gravitational pulls on the near and far parts of each galaxy, known here as a galactic tide. It is a possibility that both galaxies, which are members of the Coma Cluster, have experienced collision, and will continue colliding until they coalesce. The colors of the galaxies are peculiar. In NGC 4676A a core with some dark markings is surrounded by a bluish white remnant of spiral arms. The tail is unusual, starting out blue and terminating in a more yellowish color, despite the fact that the beginning of each arm in virtually every spiral galaxy starts yellow and terminates in a bluish color. NGC 4676B has a yellowish core and two arcs; arm remnants underneath are bluish as well. The galaxies were photographed in 2002 by the Hubble Space Telescope. In the background of the Mice Galaxies, there are over 3000 galaxies, at distances up to 13 billion light-years. """, sonification: "SonificationoftheMiceGalaxies"), `class MusicPlayer: ObservableObject { private var audioPlayer: AVPlayer? func playSound(named sonificationFileName: String){ if let url = Bundle.main.url(forResource: sonificationFileName, withExtension: "mp3"){ print("✅ Found audio file at: \(url)") audioPlayer = try? AVPlayer(url: url) audioPlayer?.play() print("🎵 Audio should now be playing!") } else { print("❌ Audio file not found: \(sonificationFileName).mp3") } } func pause(){ audioPlayer?.pause() } }
1
0
104
3d