Explore the various UI frameworks available for building app interfaces. Discuss the use cases for different frameworks, share best practices, and get help with specific framework-related questions.

All subtopics
Posts under UI Frameworks topic

Post

Replies

Boosts

Views

Activity

https://forums.developer.apple.com/forums/post/question
Hi everyone, I’m working on an iOS app using both UITableViewDiffableDataSource and SwiftUI, and I’m facing two separate but puzzling issues: UITableViewDiffableDataSource Not Reusing Cells on first applying after initial Snapshot. After applying first time it is working as expected from second time. SwiftUI View’s inside UITableViewCell onDisappear Not Triggering the on first changes of snapshot after initial snapshot. With normal UITableView it is working fine. Issue causing - it is causing player & cells to retain memory extensively Sample gist code for reproducing with diffable (DiffableTableViewExampleViewController) and working fine without diffable (RegularTableViewExampleViewController) https://gist.github.com/SURYAKANTSHARMA/d83fa9e7e0de309e27485100ba5aed17 Any insights or suggestions for these issues would be greatly appreciated! Thanks in advance!
0
0
224
Jan ’25
UITabBarController y psoition issue for iOS 18
I am trying to give bottom padding to tabbar i.e ** tabBarFrame.origin.y = view.frame.height - tabBarHeight - 30** but it is not moving up from bottom, it gets sticked to bottom = 0 and the tabbar content moving up taher than tabbar itself.. Code snippet is - `i override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let tabBarHeight: CGFloat = 70 // Custom height for the capsule tab bar var tabBarFrame = tabBar.frame tabBarFrame.size.height = tabBarHeight tabBarFrame.size.width = view.frame.width - 40 tabBarFrame.origin.y = view.frame.height - tabBarHeight - 30 tabBarFrame.origin.x = 20 tabBar.frame = tabBarFrame tabBar.layer.cornerRadius = tabBarHeight / 2 tabBar.clipsToBounds = true view.bringSubviewToFront(tabBar) }` Can anyone please help to resolve the issue for iOS 18, it is coming in iOS 18 rest previous versions are fine with the code.
0
0
328
Jan ’25
Change anchor position of view for the tvOS focus engine
I'm developing a grid of focusable elements in SwiftUI with different sizes for tvOS (similar to a tv channel grid). Because the Focus Engine calculates the next view to focus based on the center of the currently focused view, sometimes it changes focus to an unexpected view. Here's an example: Actual: Expected: Is it possible to customize the anchor point from which the focus engine traces a ray to the next view? I would prefer the leading edge in my case.
0
0
399
Jan ’25
Assertions in View bodies
I would like to be able to write something like: struct FooView: View { let foo: Foo; var body: some View { assert(foo.valid); ...... } }; but of course I can't, because "Type () cannot conform to View". What's the best way to achieve this?
3
0
412
Jan ’25
Scaling a collection of positioned views to parent (macOS)?
I have a view that lets the user position and size a bunch of subviews. I use .frame() and .position() to accomplish this. Right now, if the user resizes the window, the views stay where they are, anchored to the top-left corner. What I'd like is for the views to scale as a whole with window, maintaining their relative position, and their aspect ratios. I can apply .scaleEffect(_:anchor:) to the containing view, and it scales them the way I want, but I'm not sure how to tie it to the window. My first thought is to use a GeometryReader, but I don't really know what the "original" size would have been in order to compute a scale factor. How else might I accomplish this?
Topic: UI Frameworks SubTopic: SwiftUI
1
0
248
Jan ’25
Use of WidgetConfigurationIntent WidgetKit configurable parameter unable to internationalization of the title?
struct DeployAndWithdrawDefensesAppIntent: WidgetConfigurationIntent { // An example configurable parameter. @Parameter(title:LocalizedStringResource("ax_alarm_device_name")) } In the process of using iOS widgetKit development team a, configuration item title need language internationalization (@ Parameter (title: LocalizedStringResource (" ax_alarm_device_name "))), but found no effect. I first changed the language of the system on the iphone and found that the widget worked. However, just changing the language of the app did not take effect. Is there any way to just change the app language and make the widgets change? Thank you very much!
1
0
1k
Jan ’25
How do you make buttons inline with each other?
I want to make my buttons inline with each other, but spaced apart, a bit like the apple topbar BUT in swift. My code: struct NormalPageView: View { var body: some View { VStack { NavigationView { Form { Section { Image(systemName: "house.fill") Spacer() Image(systemName: "plus") Spacer() Image(systemName: "gearshape.fill") } } }
1
0
348
Jan ’25
macOS SwiftUI Sheets are no longer resizable (Xcode 16 beta2)
For whatever reason SwiftUI sheets don't seem to be resizable anymore. The exact same code/project produces resizable Sheets in XCode 15.4 but unresizable ones with Swift included in Xcode 16 beta 2. Tried explicitly providing .fixedSize(horizontal false, vertical: false) everywhere humanly possible hoping for a fix but sheets are still stuck at an awkward size (turns out be the minWidth/minHeight if I provide in .frame).
6
1
2.6k
Jan ’25
UIApplication.shared.open iOS 18
Making the call as: UIApplication.shared.open(websiteURL) doesn't open the browser and gives the following in the console: BUG IN CLIENT OF UIKIT: The caller of UIApplication.openURL(:) needs to migrate to the non-deprecated UIApplication.open(:options:completionHandler:). Force returning false (NO). However, making the call as: UIApplication.shared.open(websiteURL) { _ in } opens the browser and there is nothing in the cosole. Does someone understand why is this or if it's Apple's iOS 18 bug? In the iOS & iPadOS 18 RC Release Notes | Apple Developer Documentation there is a section around resolving this or something similar, unsure.
Topic: UI Frameworks SubTopic: UIKit
10
5
16k
Jan ’25
SwiftUI Buttons in a List do not highlight when tapped
SwiftUI Buttons in a List no longer highlight when tapped. Seems to have stopped highlighting after iOS 16.0 I've only tested on an iPhone/simulators so not sure if iPad has the same issue. The issue has been carried over to iOS 17 Beta 4. My app does not feel Apple like as there is no visual feedback for the user when a button in the list is pressed. Does anyone know why this is occurring? Is this a bug on Apple's end?
5
7
3.2k
Jan ’25
SwiftUI Text is larger when empty
I have a simple SwiftUI Text: Text(t) .font(Font.system(size: 9)) Strangely its ideal height seems to be larger when it is empty. I initially observed this in a custom Layout container that wasn't working quite right. Eventually I looked at the height returned by v.dimensions(in:), and found that when t is non-empty the height is 11; when empty, it's 14. Subsequently I observed similar behaviour in a regular VStack container. Has anyone seen anything similar? Are there any properties that could affect this behaviour? (This is on a watch - I don't know if that matters.)
0
0
306
Jan ’25
CarPlay - Navigation app icon
Hi, Despite having CarPlay capabilities authorised for our navigation app, our users are seeing some odd behaviour in the appearance of the icon in the sidebar menu on the side of the CarPlay display. The documentation suggests the quickbar will show the most recently used: navigation app, Open our app in CarPlay Switch to another non-navigation app via CarPlay sidebar Note that our navigation app remains in sidebar Switch back to our navigation app Search for destination, select, tap 'Let's Go' to start navigation Switch to a non-navigation app via CarPlay sidebar Note that our app is replaced by another navigation app in the sidebar (Google/Apple), despite being the most recently used Any ideas?
2
0
333
Jan ’25
Form - Multiplatform - Alignment off - HStack ?
Not sure what could cause this. the UI align differently running on iPhone versus running on Mac. If I remove the HStack, it works but I still would like to know why, and if there is a way to make it right on both platforms. Thank you here is my code @State private var viewModel = FirmwareSelectionViewModel() var body: some View { Form { Section("Setup Name") { TextField ( "", text: $viewModel.setupName ) .foregroundColor(.green ) .disableAutocorrection(true) .onSubmit { print ("On Submit") } } Section("Battery") { HStack() { Text("Volt") TextField("", value: $viewModel.Vnominal, format: .number) .textFieldStyle(.roundedBorder) .foregroundColor(.green ) #if !os(macOS) .keyboardType(.decimalPad) #endif .onChange(of: viewModel.Vnominal) { viewModel.checkEntryValidity() print("Updated Vnominal: \(viewModel.Vnominal)") } Text("Ah") TextField("", value: $viewModel.batteryCapacity, format: .number) .textFieldStyle(.roundedBorder) .foregroundColor(.green ) #if !os(macOS) .keyboardType(.decimalPad) #endif .onChange(of: viewModel.batteryCapacity) { viewModel.checkEntryValidity() print("Updated Battery Capacity: \(viewModel.batteryCapacity)") } } } Section("Firmware Type") { Picker(selection: $viewModel.selectedType, label: EmptyView()) { ForEach(TypeOfFirmware.allCases) { type in Text(type.rawValue).tag(type as TypeOfFirmware) .foregroundColor(.green ) } } .pickerStyle(SegmentedPickerStyle()) Picker(selection: $viewModel.selectedFirmware, label: EmptyView()) { ForEach(viewModel.availableFirmware) { firmware in Text(firmware.rawValue.capitalized).tag(firmware as Firmware) } } .pickerStyle(SegmentedPickerStyle()) } } .onChange(of: viewModel.selectedType) { viewModel.resetFirmwareSelection() } .navigationTitle("Firmware Selection") } }
Topic: UI Frameworks SubTopic: SwiftUI
0
0
177
Jan ’25
TextField.preferesDefaultFocus does not work in alerts
Hi, I am having trouble setting default focus on a TextField that is inside of an alert. I expected TextField to receive default focus when alert is presented but result is that TextField does not receive default focus. This is happening on macOS 15.2, Swift (SwiftUI), Xcode 16.2 but hasn't worked on previous versions as well. Example: ContentView().alert("Sample Alert", isPresented: $present) { AlertView() } message: { Text("Sample alert message.") } struct AlertView: View { @Namespace private var namespace @Environment(\.dismiss) private var dismiss @State private var text = "" var body: some View { VStack { TextField(text: $text, prompt: Text("Enter text")) {} .onSubmit { var _ = print(text) dismiss() } .autocorrectionDisabled() .lineLimit(1) .prefersDefaultFocus(in: namespace) Button("OK") { dismiss() } Button("Cancel", role: .cancel) { dismiss() } } .focusScope(namespace) } }
Topic: UI Frameworks SubTopic: SwiftUI
1
0
205
Jan ’25
VStack Alignment Issue
Hi Apple developer, I'm totally new in the development world using SwiftUI with just a little experience of Flutter. Currently I'm struggling with the combination of VStack and the alignment of the sub views. I'm using a LazyVGrid with multiple Rectangles and overlays inside. The overlay contains a VStack with a leading alignment. And here is the problem. I framed them with a border to visualize the limits of these views. But it seams, that the leading alignment is not working properly. There is a large gap on the left side of the Image() and Text() views and I don't know why. I'm very happy for any advice. Here is my code of this view. Thanks a lot! import SwiftUI import SwiftData extension UIScreen { static let screenWidth: CGFloat = UIScreen.main.bounds.size.width static let screenHeight: CGFloat = UIScreen.main.bounds.size.height static let screenSize: CGSize = UIScreen.main.bounds.size } struct TestView: View { let constants: Constants = Constants() let columnCount: Int = 2 let gridSpacing: CGFloat = 10 let gridRadius: CGFloat let gridWidth: CGFloat let gridHeight: CGFloat let gridItems = [ Item(title: "Total", color: Color.gray, image: "dollarsign.circle.fill") ] @State private var isSheetPresented: Bool = false init() { gridWidth = UIScreen._screenWidth / 2 - 3 * gridSpacing gridHeight = 1.25 * gridWidth gridRadius = gridWidth / 7.5 } var body: some View { NavigationStack { ScrollView(.vertical) { LazyVGrid(columns: Array( repeating: .init(.flexible(), spacing: -2 * gridSpacing), count: columnCount), spacing: 2 * gridSpacing) { ForEach(gridItems, id: \.title) { item in RoundedRectangle(cornerRadius: gridRadius, style: .continuous) .fill(item.color.gradient) .frame(width: gridWidth, height: gridHeight) .overlay( VStack(alignment: .leading) { Image(systemName: item.image) .colorInvert() .font(.system(size: 30)) .border(Color.yellow) Spacer() Text(item.title) .font(.system(size: 20)) .foregroundColor(.white) .border(Color.yellow) } .padding([.top, .bottom]) .frame(maxWidth: .infinity) .border(Color.black) ) } }.padding(.top) } .navigationTitle("Test View") .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .topBarTrailing) { Menu { Button("Add", action: {}) } label: { Image(systemName: "ellipsis.circle") } } } } } } struct Item: Identifiable { let id: UUID = UUID() let title: String let color: Color let image: String } #Preview { TestView() }
Topic: UI Frameworks SubTopic: SwiftUI
1
0
370
Jan ’25
Poor ScrollView performance
Hello, I have a scroll view that when it appears I get a constant stream of warnings from the console: CGBitmapContextInfoCreate: CGColorSpace which uses extended range requires floating point or CIF10 bitmap context This happens whether or not I'm actively scrolling, so maybe it's not a scroll view issue at all? The reason I initially thought it was a scrollView issue was because when I scrolled the scrolling was no longer smooth, it was pretty choppy. Also, I only get these warnings when I run my code on a real device - I do not get these on any simulators. Could it be the mesh gradient causing an issue? I'm not sure what's causing the issue so I apologize in advance for what may be irrelevant code. struct ModernStoryPicker: View { @Environment(CategoryPickerViewModel.self) var categoryPickerViewModel @EnvironmentObject var navigationPath: GrowNavigationState @State private var hasPreselectedStory: Bool = false @State private var storyGenerationType: StoryGenerationType = .arabicCompanion var userInstructions: String { if categoryPickerViewModel.userInputCategory.isEmpty { "Select a category" } else if categoryPickerViewModel.userInputSubCategory.isEmpty { "Select a subcategory" } else { "Select a story" } } var body: some View { ZStack { MeshGradient(width: 3, height: 3, points: [ [0.0, 0.0], [0.5, 0.0], [1.0, 0.0], [0.0, 0.5], [0.9, 0.3], [1.0, 0.5], [0.0, 1.0], [0.5, 1.0], [1.0, 1.0] ], colors: [ .orange, .indigo, .orange, .blue, .blue, .cyan, .green, .indigo, .pink ]) .ignoresSafeArea() VStack { Picker("", selection: $storyGenerationType) { ForEach(StoryGenerationType.allCases) { type in Text(type.rawValue).tag(type) } }.pickerStyle(.segmented) Text(userInstructions) .textScale(.secondary) automatedOrUserStories() Spacer() }.padding() } .onAppear {...} } @ViewBuilder func automatedOrUserStories() -> some View { switch storyGenerationType { case .userGenerated: VStack { Spacer() Text("Coming soon!") } case .arabicCompanion: VStack { // TODO: Unnecessary passing of data, only the 2nd view really needs all these props CategoryPickerView( categories: categoryPickerViewModel.mainCategories(), isSubCategory: false, selectionColor: .blue ) CategoryPickerView( categories: categoryPickerViewModel.subCategories(), isSubCategory: true, selectionColor: .purple ) ScrollView(.horizontal) { HStack { if categoryPickerViewModel.booksForCategories.isEmpty { Text("More books coming soon!") } ForEach(categoryPickerViewModel.booksForCategories) { bookCover in Button(action: { // navigates to BookDetailView.swift navigationPath.path.append(bookCover) }) { ModernStoryCardView( loadedImage: categoryPickerViewModel.imageForBook(bookCover), bookCover: bookCover ) .scrollTransition(axis: .horizontal) { content, phase in content .scaleEffect(phase.isIdentity ? 1 : 0.5) .opacity(phase.isIdentity ? 1 : 0.8) } }.buttonStyle(.plain) } }.scrollTargetLayout() } .contentMargins(80, for: .scrollContent) .scrollTargetBehavior(.viewAligned) }.padding() } } } struct CategoryPickerView: View { @Environment(CategoryPickerViewModel.self) var viewModel let categories: [String] let isSubCategory: Bool let selectionColor: Color var body: some View { ScrollView(.horizontal) { HStack { ForEach(categories, id: \.self) { category in Button(action: { withAnimation { selectCategory(category) } }) { TextRoundedRectangleView(text: category, color: effectiveColor(for: category)) .tag(category) }.buttonStyle(.plain) } } }.scrollIndicators(.hidden) } private func selectCategory(_ string: String) { if !isSubCategory { viewModel.userInputCategory = string } else { viewModel.userInputSubCategory = string } } private func effectiveColor(for category: String) -> Color { let chosenCategory = isSubCategory ? viewModel.userInputSubCategory : viewModel.userInputCategory if category == chosenCategory { return selectionColor } return .white } }
4
0
652
Jan ’25
Type 'AVPlayer.Type' cannot conform to 'ObservableObject'
I'm having the following issue: Type 'AVPlayer.Type' cannot conform to 'ObservableObject' struct MusicEditorView: View { @ObservedObject var audioPlayer = AVPlayer and this is the class: class MusicPlayer: ObservableObject { private var audioPlayer: AVPlayer? private var timer: Timer? func playSound(named sFileName: String){ if let url = Bundle.main.url(forResource: sFileName, withExtension: "mp3"){ audioPlayer = try? AVPlayer(url: url) audioPlayer?.play() } } func pause(){ audioPlayer?.pause() } func getcurrentProgress() -> Double{ guard let currentTime = audioPlayer?.currentItem?.currentTime().seconds else { return 0 } guard let duration = audioPlayer?.currentItem?.duration.seconds else { return 0 } return duration > 0 ? (currentTime / duration) * 100 : 0 } func startProgressTimer(updateProgress: @escaping (Double, Double) -> Void){ timer?.invalidate() timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in guard let currentTime = self.audioPlayer?.currentItem?.currentTime().seconds else { return } guard let duration = self.audioPlayer?.currentItem?.duration.seconds else { return } updateProgress(currentTime, duration) } } func stopProgressTimer(){ timer?.invalidate() } struct Sound: Identifiable, Codable { var id = UUID() var name: String var fileName: String } } }
1
0
431
Jan ’25