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

Navigation title in master splitview panel wrong colour with dark mode and hard scrollEdgeEffect
The navigation title color is wrong (dark on dark background) when applying hard scrolledgeeffectstyle. Illustrated by code example. In simulator or physical device. Changing scrollEdgeEffectStyle to soft resolves the issue. As does changing the listStyle. @main struct AppView: App { var body: some Scene { WindowGroup { NavigationSplitView { NavigationStack { Section { NavigationLink(destination: OptionsView()) { Label("More Options", systemImage: "gearshape") } .isDetailLink(false) } header: { Text("WITH OPTIONS").bold() } .navigationTitle("TESTING") } } detail: { Text("DETAIL") } .preferredColorScheme(.dark) } } } struct OptionsView: View { var body: some View { List { Text("List Item") } .listStyle(.plain) .navigationTitle("MORE OPTIONS TITLE") .scrollEdgeEffectStyle(.hard, for: .all) } } Submittted FB20811402 Bug appears in Landscape mode for iPhone only. Any orientation for iPad.
Topic: UI Frameworks SubTopic: SwiftUI
7
0
158
2w
Problem with having Toggle inside a GeometryReader with onChange handler
Hi, I've come across this weird issue which I think is probably a bug, but before I file a radar I'll ask here just in case I'm doing something in a weird way. I found that on macOS if I have a Toggle inside a GeometryReader inside a Tab, and I have an onChange handler for some property of the geometry (even if the onChange doesn't do anything) then the second time I switch to that tab, I get a whole lot of 'AttributeGraph: cycle detected through attribute' logs and the app hangs. It doesn't matter whether it's on the first or second tab, but I've put it in the first tab here. This only happens on macOS… at first I thought it also happened on iOS, but it turned out that was a similar symptom caused by an unrelated issue. Here is some code that reproduces the issue: TabView { Tab("tab 1", systemImage: "rainbow") { Toggle("This toggle is fine", isOn: .constant(true)) } Tab("tab 2", systemImage: "checkmark") { GeometryReader { geometry in VStack { //but with this toggle here, combined with the onChange handler, //the second time we switch to this tab we get the hang Toggle("This toggle causes a hang the second time we switch to this tab", isOn: .constant(true)) //if we comment out the toggle and uncomment the text instead, //it's fine. //Text("This text does not cause a hang") }.onChange(of: geometry.size.height) { //even if this is empty, having it here makes //the app hang when switching to this tab for the second time. //and emit 'AttributeGraph: cycle detected through attribute' in the log } } } } .padding() If I remove either the Toggle or the onChange handler, there is no problem. I can put all sorts of other things in the tab, but as soon as I put a toggle there, I get this hang. For now I've worked around it by putting Toggles in a settings sheet rather than directly on the tab, but since there's plenty of space on macOS it would be nice to have them directly on the tab. One thing that's weird is that if I put this same code in the Settings window of an app, it doesn't seem to have the problem — maybe because the tabs are a different style there.
Topic: UI Frameworks SubTopic: SwiftUI Tags:
2
0
46
2w
How to temporarily hide another app's Dynamic Island?
Hello, I have a question regarding the control over the Dynamic Island UI when my app is in the foreground. Scenario: A user is playing a song on Apple Music, so its Live Activity is active and visible in the Dynamic Island. Then, the user opens my app. Desired Behavior: While my app is in the foreground, I would like to temporarily hide or dismiss the dynamic island from Apple Music to provide a more immersive experience. When the user navigates away from my app, it's perfectly fine for the Dynamic Island to show dynamic island again. Is there an API that allows an app to temporarily suppress a Live Activity that was initiated by another application? My understanding of the iOS sandbox model suggests this might not be possible for security and privacy reasons, but I wanted to confirm if there's an intended way to handle this, especially for full-screen apps like games or video players. Thank you!
2
0
55
2w
ScrollView with .viewAligned and .scrollPosition() not updating on orientation (size) changes
The scroll position is not updated when orientation changes in a ScrollView with .scrollTargetBehavior(.viewAligned) and .scrollPosition(). import SwiftUI struct ContentView: View { let colors: [Color] = [.red, .yellow, .cyan, .blue, .teal, .brown, .orange, .indigo] @State private var selected: Int? = 0 var body: some View { ScrollView(.horizontal) { HStack(spacing: 0) { ForEach(0..<colors.count, id: \.self) { index in Rectangle() .fill(colors[index]) .containerRelativeFrame(.horizontal) .overlay { Text(colors[index].description) } } } .scrollTargetLayout() } .scrollPosition(id: $selected) .scrollTargetBehavior(.viewAligned) } } #Preview { ContentView() } @main struct ViewAlignedScrollBugApp: App { var body: some Scene { WindowGroup { ContentView() } } } Tested on Xcode 15.3 (15E204a), iOS 17.3.1 iPhone, iOS 17.4 Simulator. Bug report FB13685677 filed with Apple.
2
1
826
2w
SpriteKit/RealityKit + SwiftUI Performance Regression on iOS 26
Hi, Toggling a SwiftUI menu in iOS 26 significantly reduces the framerate of an underlying SKView or ARView. Below are test cases for SpriteKit and RealityKit. I ran these tests on iOS 26.1 Beta using an iPhone 13 (A15 chip). Results were similar on iOS 26.0.1. Both scenes consist of circles and balls bouncing on the ground. The restitution of the physics bodies is set for near-perfect elasticity, so they keep bouncing indefinitely. In both SKView and ARView, the framerate drops significantly whenever the SwiftUI menu is toggled. The menu itself is simple and uses standard SwiftUI animations and styling. SpriteKit import SpriteKit import SwiftUI class SKRestitutionScene: SKScene { override func didMove(to view: SKView) { view.contentMode = .center size = view.bounds.size scaleMode = .resizeFill backgroundColor = .darkGray anchorPoint = CGPoint(x: 0.5, y: 0.5) let groundWidth: CGFloat = 300 let ground = SKSpriteNode(color: .gray, size: CGSize(width: groundWidth, height: 10)) ground.physicsBody = SKPhysicsBody(rectangleOf: ground.size) ground.physicsBody?.isDynamic = false addChild(ground) let circleCount = 5 let spacing: CGFloat = 60 let totalWidth = CGFloat(circleCount - 1) * spacing let startX = -totalWidth / 2 for i in 0..<circleCount { let circle = SKShapeNode(circleOfRadius: 18) circle.fillColor = .systemOrange circle.lineWidth = 0 circle.physicsBody = SKPhysicsBody(circleOfRadius: 18) circle.physicsBody?.restitution = 1 circle.physicsBody?.linearDamping = 0 let x = startX + CGFloat(i) * spacing circle.position = CGPoint(x: x, y: 150) addChild(circle) } } override func willMove(from view: SKView) { self.removeAllChildren() } } struct SKRestitutionView: View { var body: some View { ZStack { SpriteView(scene: SKRestitutionScene(), preferredFramesPerSecond: 120) .ignoresSafeArea() VStack { Spacer() Menu { Button("Edit", systemImage: "pencil") {} Button("Share", systemImage: "square.and.arrow.up") {} Button("Delete", systemImage: "trash") {} } label: { Text("Menu") } .buttonStyle(.glass) } .padding() } } } #Preview { SKRestitutionView() } RealityKit import RealityKit import SwiftUI struct ARViewPhysicsRestitution: UIViewRepresentable { let arView = ARView() func makeUIView(context: Context) -> some ARView { arView.contentMode = .center arView.cameraMode = .nonAR arView.automaticallyConfigureSession = false arView.environment.background = .color(.gray) // MARK: Root let anchor = AnchorEntity() arView.scene.addAnchor(anchor) // MARK: Camera let camera = Entity() camera.components.set(PerspectiveCameraComponent()) camera.position = [0, 1, 4] camera.look(at: .zero, from: camera.position, relativeTo: nil) anchor.addChild(camera) // MARK: Ground let groundWidth: Float = 3.0 let ground = Entity() let groundMesh = MeshResource.generateBox(width: groundWidth, height: 0.1, depth: groundWidth) let groundModel = ModelComponent(mesh: groundMesh, materials: [SimpleMaterial(color: .white, roughness: 1, isMetallic: false)]) ground.components.set(groundModel) let groundShape = ShapeResource.generateBox(width: groundWidth, height: 0.1, depth: groundWidth) let groundCollision = CollisionComponent(shapes: [groundShape]) ground.components.set(groundCollision) let groundPhysicsBody = PhysicsBodyComponent( material: PhysicsMaterialResource.generate(friction: 0, restitution: 0.97), mode: .static ) ground.components.set(groundPhysicsBody) anchor.addChild(ground) // MARK: Balls let ballCount = 5 let spacing: Float = 0.4 let totalWidth = Float(ballCount - 1) * spacing let startX = -totalWidth / 2 let radius: Float = 0.12 let ballMesh = MeshResource.generateSphere(radius: radius) let ballMaterial = SimpleMaterial(color: .systemOrange, roughness: 1, isMetallic: false) let ballShape = ShapeResource.generateSphere(radius: radius) for i in 0..<ballCount { let ball = Entity() let ballModel = ModelComponent(mesh: ballMesh, materials: [ballMaterial]) ball.components.set(ballModel) let ballCollision = CollisionComponent(shapes: [ballShape]) ball.components.set(ballCollision) var ballPhysicsBody = PhysicsBodyComponent( material: PhysicsMaterialResource.generate(friction: 0, restitution: 0.97), /// 0.97 for near perfect elasticity mode: .dynamic ) ballPhysicsBody.linearDamping = 0 ballPhysicsBody.angularDamping = 0 ball.components.set(ballPhysicsBody) let shadow = GroundingShadowComponent(castsShadow: true) ball.components.set(shadow) let x = startX + Float(i) * spacing ball.position = [x, 1, 0] anchor.addChild(ball) } return arView } func updateUIView(_ uiView: UIViewType, context: Context) { } } struct PhysicsRestitutionView: View { var body: some View { ZStack { ARViewPhysicsRestitution() .ignoresSafeArea() .background(.black) VStack { Spacer() Menu { Button("Edit", systemImage: "pencil") {} Button("Share", systemImage: "square.and.arrow.up") {} Button("Delete", systemImage: "trash") {} } label: { Text("Menu") } .buttonStyle(.glass) } .padding() } } } #Preview { PhysicsRestitutionView() }
2
0
175
2w
iPadOS 26 UISearchController bug causing presented view controller to be dismissed
Under iPadsOS 26.0 and 26.1, if a view controller is presented with a presentation style of fullScreen or pageSheet, and the view controller is setup with a UISearchController that has obscuresBackgroundDuringPresentation set to true, then when cancelling the search the view controller is being dismissed when it should not be. To replicate, create a new iOS project based on Swift/Storyboard using Xcode 26.0 or Xcode 26.1. Update ViewController.swift with the following code: import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .systemBackground title = "Root" navigationItem.rightBarButtonItems = [ UIBarButtonItem(title: "Full", primaryAction: .init(handler: { _ in self.showModal(with: .fullScreen) })), UIBarButtonItem(title: "Page", primaryAction: .init(handler: { _ in self.showModal(with: .pageSheet) })), UIBarButtonItem(title: "Form", primaryAction: .init(handler: { _ in self.showModal(with: .formSheet) })), ] } private func showModal(with style: UIModalPresentationStyle) { let vc = ModalViewController() let nc = UINavigationController(rootViewController: vc) // This triggers the double dismiss bug when set to either pageSheet or fullScreen. // If set to formSheet then it works fine. // Bug is only on iPad with iPadOS 26.0 or 26.1 beta 2. // Works fine on iPhone (any iOS) and iPadOS 18 as well as macOS 26.0 (not tested with other versions of macOS). nc.modalPresentationStyle = style self.present(nc, animated: true) } } Then add a new file named ModalViewController.swift with the following code: import UIKit class ModalViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() title = "Modal" view.backgroundColor = .systemBackground setupSearch() } private func setupSearch() { let sc = UISearchController(searchResultsController: UIViewController()) sc.delegate = self // Just for debugging - being set or not does not affect the bug sc.obscuresBackgroundDuringPresentation = true // Critical to reproducing the bug navigationItem.searchController = sc navigationItem.preferredSearchBarPlacement = .stacked } // When the search is cancelled by tapping on the grayed out area below the search bar, // this is called twice when it should only be called once. This happens only if the // view controller is presented with a fullScreen or pageSheet presentation style. // The end result is that the first call properly dismisses the search controller. // The second call results in this view controller being dismissed when it should not be. override func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) { print("dismiss ViewController") // Set breakpoint on the following line super.dismiss(animated: flag, completion: completion) } } extension ModalViewController: UISearchControllerDelegate { func willDismissSearchController(_ searchController: UISearchController) { print("willDissmissSearchController") } func didDismissSearchController(_ searchController: UISearchController) { print("didDismissSearchController") } } Build and run the app on a simulated or real iPad running iPadOS 26.0 or 26.1 (beta 2). A root window appears with 3 buttons in the navbar. Each button displays the same view controller but with a different modalPresentationStyle. Tap the Form button. This displays a modal view controller with formSheet style. Tap on the search field. Then tap on the grayed out area of the view controller to cancel the search. This all works just fine. Dismiss the modal (drag it down). Now tap either the Page or Full button. These display the same modal view controller with pageSheet or fullScreen style respectively. Tap on the search field. Then tap on the grayed out area of the view controller to cancel the search. This time, not only is the search cancelled, but the view controller is also dismissed. This is because the view controller’s dismiss(animated:completion:) method is being called twice. See ViewController.swift for the code that presents the modal. See ModalViewController.swift for the code that sets up the search controller. Both contain lots of comments. Besides the use of fullScreen or pageSheet presentation style to reproduce the bug, the search controller must also have its obscuresBackgroundDuringPresentation property set to true. It’s the tap on that obscured background to cancel the search that results in the double call to dismiss. With the breakpoint set in the overloaded dismiss(animated:completion:) function, you can see the two stack traces that lead to the call to dismiss. When presented as a formSheet, the 2nd call to dismiss is not being made. This issue does not affect iPadOS 18 nor any version of iOS on iPhones. Nor does it affect the app using Mac Catalyst on macOS 26.0 (untested with macOS 15 or 26.1). In short, it is expected that cancelling the search in a presented view controller should not also result in the view controller being dismissed. Tested with Xcode 26.1 beta 2 and Xcode 26.0. Tested with iPadOS 26.1 beta 2 (real and simulated) and iPadOS 26.0 (simulated). A version of this post was submitted as FB20569327
2
1
272
2w
How to handle alert when deleting row from List
This is another issue found after changing to use a @StateObject for my data model when populating a List. Previous issue is here: https://developer.apple.com/forums/thread/805202 - the entire List was being redrawn when one value changed, and it jumped to the top. Here's some code: struct ItemListView: View { @State private var showAlert: Bool = false ... fileprivate func drawItemRow(_ item: ItemDetails) -> some View { return ItemRow(item: item) .id(item.id) .swipeActions(edge: .trailing, allowsFullSwipe: false) { RightSwipeButtons(showAlert: $showAlert, item: item) } } ... List { ForEach(modelData.filteredItems.filter { !$0.archived }) { item in drawItemRow(item) } } ... .alert("Delete Item"), isPresented: $showAlert) { Button("Yes, delete", role: .destructive) { deleteItem(item.id) // Not important how this item.id is gained } Button("Cancel", role: .cancel) { } } message: { Text("Are you sure you want to delete this item? You cannot undo this.") } } struct RightSwipeButtons: View { @Binding var showAlert: Bool var body: some View { Button { showAlert = true } label: { Label("", systemImage: "trash") } } } The issue I have now is that when you swipe from the right to show the Delete button, and tap it, the alert is displayed but the list has jumped back to the top again. At this point you haven't pressed the delete button on the alert. Using let _ = Self._printChanges() on both the ItemsListView and the individual ItemRows shows this: ItemsListView: _showAlert changed. ItemRow: @self, @identity, _accessibilityDifferentiateWithoutColor changed. So yeah, that's correct, showAlert did change in ItemsListView, but why does the entire view get redrawn again, and fire me back to the top of the list? You'll notice that it also says _accessibilityDifferentiateWithoutColor changed on the ItemRows, so I commented out their use to see if they were causing the issue, and... no. Any ideas? (Or can someone provide a working example of how to ditch SwiftUI's List and go back to a UITableView...?)
3
0
167
2w
PHPickerViewController unusable via Mac Catalyst on macOS 26 when interface is "Scaled to Match iPad"
There is a serious usability issue with PHPickerViewController in a UIKit app running on macOS 26 via Mac Catalyst when the Mac Catalyst interface is set to “Scaled to Match iPad”. Mouse click and other pointer interactions do not take place in the correct position. This means you have to click in the wrong position to select a photo and to close the picker. This basically makes it unusable. To demonstrate, use Xcode 26 on macOS 26 to create a new iOS app project based on Swift/Storyboard. Then update ViewController.swift with the following code: import UIKit import PhotosUI class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() var cfg = UIButton.Configuration.plain() cfg.title = "Photo Picker" let button = UIButton(configuration: cfg, primaryAction: UIAction(handler: { _ in self.showPicker() })) button.translatesAutoresizingMaskIntoConstraints = false view.addSubview(button) NSLayoutConstraint.activate([ button.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor), button.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor), ]) } private func showPicker() { var config = PHPickerConfiguration() config.selectionLimit = 10 config.selection = .ordered let vc = PHPickerViewController(configuration: config) vc.delegate = self self.present(vc, animated: true) } } extension ViewController: PHPickerViewControllerDelegate { func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) { print("Picked \(results.count) photos") dismiss(animated: true) } } Then go to the "Supported Destinations" section of the project target. Add a "Mac (Mac Catalyst)" destination. Then under the "Deployment Information" section, make sure the "Mac Catalyst Interface" setting is "Scaled to Match iPad". Then build and run the app on a Mac (using the Mac Catalyst destination) with macOS 26.0.1. Make sure the Mac has a dozen or so pictures in the Photo Library to fully demonstrate the issue. When the app is run, a simple screen appears with one button in the middle. Click the button to bring up the PHPickerViewController. Now try to interact with the picker interface. Note that all pointer interactions are in the wrong place on the screen. This makes it nearly impossible to choose the correct photos and close the picker. Quit the app. Select the project and go to the General tab. In the "Deployment Info" change the “Mac Catalyst Interface” setting to “Optimize for Mac” and run the app again. Now the photo picker works just fine. If you run the app on a Mac running macOS 15 then the photo picker works just fine with either “Mac Catalyst Interface” setting. The problem only happens under macOS 26.0 (I do not have macOS 26.1 beta to test) when the “Mac Catalyst Interface” setting is set to “Scaled to Match iPad”. This is critical for my app. I cannot use “Optimize for Mac”. There are far too many issues with that setting (I use UIStepper and UIPickerView to start). So it is critical to the usability of my app under macOS 26 that this issue be resolved. It is expected that PHPickerViewController responds correctly to pointer events on macOS 26 when running a Mac Catalyst app set to “Scaled to Match iPad”. A version of this has been filed as FB20503207
12
4
572
2w
Adding a sublayer to a Glass UIButton to work as a border
I want to set a sublayer to a UIButton's layer, using a Glass or Prominent Glass configuration, setting the strokeColor property acting as the border to a UIButton's bounds. The main issue I'm facing is not being able to follow the button's bounds when it changes as it expands on touch down. Is there an expected pattern for applying sublayers to a UIButton and make it follow UIButton's bounds as it changes during interactions?
Topic: UI Frameworks SubTopic: UIKit Tags:
0
0
38
2w
NSStagedMigrationManager shortcomings
It seems to me that NSStagedMigrationManager has algorithmic issues. It doesn't perform staged migration, if all its stages are NSLightweightMigrationStage. You can try it yourself. There is a test project with three model versions V1, V2, V3, V4. Migrating V1->V2 is compatible with lightweight migration, V2->V3, V3->V4 is also compatible, but V1->V3 is not. I have following output: Migrating V1->V2, error: nil Migrating V2->V3, error: nil Migrating V3->V4, error: nil Migrating V1->V3, no manager, error: Optional("Persistent store migration failed, missing mapping model.") Migrating V1->V3, lightweight[1, 2, 3], error: Optional("Persistent store migration failed, missing mapping model.") Migrating V1->V3, lightweight[1]->lightweight[2]->lightweight[3], error: Optional("Persistent store migration failed, missing mapping model.") Migrating V1->V3, custom[1->2]->lightweight[3], error: nil Migrating V1->V3, lightweight[1]->custom[2->3], error: nil Migrating V1->V3, custom[1->2]->custom[2->3], error: nil Migrating V1->V4, error: Optional("Persistent store migration failed, missing mapping model.") Migrating V2->V4, error: nil Migrating V1->V4, custom[1->2]->lightweight[3, 4], error: nil Migrating V1->V4, lightweight[3, 4]->custom[1->2], error: Optional("A store file cannot be migrated backwards with staged migration.") Migrating V1->V4, lightweight[1, 2]->lightweight[3, 4], error: Optional("Persistent store migration failed, missing mapping model.") Migrating V1->V4, lightweight[1]->custom[2->3]->lightweight[4], error: nil Migrating V1->V4, lightweight[1,4]->custom[2->3], error: nil Migrating V1->V4, custom[2->3]->lightweight[1,4], error: Optional("Persistent store migration failed, missing mapping model.") I think that staged migration should satisfy the following rules for two consecutive stages: Any version of lightweight stage to any version of lightweight stage; Any version of lightweight stage to current version of custom stage; Next version of custom stage to any version of lightweight stage; Next version of custom stage to current version of custom stage. However, rule 1 doesn't work, because migration manager skips intermediate versions if they are inside lightweight stages, even different ones. Note that lightweight[3, 4]->custom[1->2] doesn't work, lightweight[1,4]->custom[2->3] works, but custom[2->3]->lightweight[1,4] doesn't work again. Would like to hear your opinion on that, especially, from Core Data team, if possible. Thanks!
4
0
186
2w
Swiftui Picker with optional value selected in picker
First the model: import SwiftData //Model one: type of contract, i.e. Firm Fixed Price, etc @Model final class TypeOfContract { var contracts: [Contract] @Attribute(.unique) var typeName: String @Attribute(.unique) var typeCode: String var typeDescription: String init(contracts: [Contract], typeName: String = "", typeCode: String = "", typeDescription: String = "") { self.contracts = contracts self.typeName = typeName self.typeCode = typeCode self.typeDescription = typeDescription } } //Model two: the Contract @Model final class Contract { var contractType: TypeOfContract? var costReports: [CostReport] @Attribute(.unique) var contractNumber: String @Attribute(.unique) var contractName: String var startDate: Date var endDate: Date var contractValue: Decimal var contractCompany: String var contractContact: String var contactEmail: String var contactPhone: String var contractNotes: String init(contractType: TypeOfContract?, costReports: [CostReport], contractNumber: String = "", contractName: String = "", startDate: Date = .now, endDate: Date = .now, contractValue: Decimal = 0.00, contractCompany: String = "", contractContact: String = "", contactEmail: String = "", contactPhone: String = "", contractNotes: String = "") { self.contractType = contractType self.costReports = costReports self.contractNumber = contractNumber self.contractName = contractName self.startDate = startDate self.endDate = endDate self.contractValue = contractValue self.contractCompany = contractCompany self.contractContact = contractContact self.contactEmail = contactEmail self.contactPhone = contactPhone self.contractNotes = contractNotes } } //Model Three: The Cost Reports @Model final class CostReport { var contract: Contract? var periodStartDate: Date var periodEndDate: Date var bCWP: Double //Budgeted Cost Work Performed var aCWP: Double //Actual Cost Work Performed var bCWS: Double //Budgeted Cost Work Scheduled //Calculated fields init(contract: Contract?, periodStartDate: Date = .now, periodEndDate: Date = .now, bCWP: Double = 0.0, aCWP: Double = 0.0, bCWS: Double = 0.0) { self.contract = contract self.periodStartDate = periodStartDate self.periodEndDate = periodEndDate self.bCWP = bCWP self.aCWP = aCWP self.bCWS = bCWS } } Now the code for the Picker ```import SwiftUI import SwiftData struct EnterNewContract: View { @Environment(\.modelContext) var modelContext @Query(sort: \TypeOfContract.typeName) private var typeOfContracts: [TypeOfContract] @Query private var contracts: [Contract] @State private var costReports: [CostReport] = [] @State private var contractType: [TypeOfContract]? @State private var contractNumber: String = "" @State private var contractName: String = "" @State private var startDate: Date = Date() @State private var endDate: Date = Date() @State private var contractValue: Decimal = 0 @State private var contractCompany: String = "" @State private var contractContact: String = "" @State private var contactEmail: String = "" @State private var contactPhone: String = "" @State private var contractNotes: String = "" var body: some View { Form { VStack { Section(header: Text("Enter New Contract") .foregroundStyle(.green) .font(.headline)){ Picker("Select a type of contract", selection: $contractType) {Text("Select type").tag(nil as TypeOfContract?) ForEach(typeOfContracts, id: \.self) { typeOfContracts in Text(typeOfContracts.typeName) .tag(typeOfContracts as TypeOfContract?) } } TextField("Contract Number", text: $contractNumber) .frame(width: 800, height: 40) TextField("Contract Name", text: $contractName) .frame(width: 800, height: 40) DatePicker("Contract Start Date", selection: $startDate, displayedComponents: [.date]) DatePicker("Contract End Date", selection: $endDate, displayedComponents: [.date]) } } } } } The code works, for the most part. The selection I make from the list does not appear. Instead there is just a shaded empty box . Also, I need to select my selection choice twice before the check mark to appear. To see the choices and my selection I must click on the empty shaded box. What did I do wrong
2
0
168
2w
UINavigationBar setting button yields multple constraint errors
Hey all in iOS26.1 i seem to be getting a bunch of Constraint errors when setting the rightBarButtonItem leftBarButtonItem. Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) ( "<NSAutoresizingMaskLayoutConstraint:0x6000021a2a30 h=--& v=--& _TtCC5UIKit19NavigationButtonBar15ItemWrapperView:0x13d84c080.width == 0 (active)>", "<NSLayoutConstraint:0x6000021a1cc0 _TtCC5UIKit19NavigationButtonBar15ItemWrapperView:0x13d84c080.leading == _UIButtonBarButton:0x106cd3ed0.leading (active)>", "<NSLayoutConstraint:0x6000021a1d10 H:[_UIButtonBarButton:0x106cd3ed0]-(0)-| (active, names: '|':_TtCC5UIKit19NavigationButtonBar15ItemWrapperView:0x13d84c080 )>", "<NSLayoutConstraint:0x6000021a19f0 'IB_Leading_Leading' H:|-(2)-[_UIModernBarButton:0x106cc80b0] (active, names: '|':_UIButtonBarButton:0x106cd3ed0 )>", "<NSLayoutConstraint:0x6000021a1a40 'IB_Trailing_Trailing' H:[_UIModernBarButton:0x106cc80b0]-(2)-| (active, names: '|':_UIButtonBarButton:0x106cd3ed0 )>" ) Will attempt to recover by breaking constraint <NSLayoutConstraint:0x6000021a1a40 'IB_Trailing_Trailing' H:[_UIModernBarButton:0x106cc80b0]-(2)-| (active, names: '|':_UIButtonBarButton:0x106cd3ed0 )> Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger. The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKitCore/UIView.h> may also be helpful. Curious if im setting something wrong, or maybe i can just ignore these (granted they are annoying in my logs) This wasnt happening in iOS 26.0
Topic: UI Frameworks SubTopic: UIKit
2
1
122
2w
Prevent cell from scrolling out of view
I have a UITableView with multiple screens worth of cells and the height of the cells vary. At a certain point in the user's workflow, I want to prevent a specific cell from being scrolled out of view. I want it to allow it to scroll from the top of the screen to the bottom but not out of view. I'm trying to solve this by updating the tableView.contentInset property with the following logic... let visibleContentHeight = tableView.bounds.height var insetTop = (cell.frame.origin.y - visibleContentHeight) insetTop = (insetTop < 0) ? 0 : -insetTop var insetBottom = tableView.contentSize.height - (cell.frame.origin.y + cell.frame.height + visibleContentHeight) insetBottom = (insetBottom < 0) ? 0 : -insetBottom tableView.contentInset = UIEdgeInsets(top: insetTop, left: 0, bottom: insetBottom, right: 0) This doesn't seem to work exactly right. When scrolling, the cell's top/bottom doesn't line up with the view's top/bottom. And the difference between those margins is not consistent. Printing out some the raw values, it looks like the cell's frame.origin sometimes changes as well as tableView.contentSize.height. I assume the system is using tableView.estimatedRowHeight to calculate the table's content height for the cells that are not loaded, so that's probably another factor. Is setting contentInset not the way to do this? Is there another way? Is there an error in my math/logic? I must be missing something. Any help is appreciated. Thanks.
Topic: UI Frameworks SubTopic: UIKit
1
0
58
2w
SwiftUI TextField selection - strange initial values with iOS
When using a TextField with axis to set to .vertical on iOS, it sets a bound selection parameter to an erroneous value. Whilst on MacOS it performs as expected. Take the following code: import SwiftUI @main struct SelectionTestApp: App { var body: some Scene { WindowGroup { ContentView() } } } struct ContentView: View { @FocusState private var isFocused: Bool @State private var text = "" @State private var textSelection: TextSelection? = nil var body: some View { TextField("Label", text: $text, selection: $textSelection, axis: .vertical) .onChange(of: textSelection, initial: true) { if let textSelection { print("textSelection = \(textSelection)") } else { print("textSelection = nil") } } .focused($isFocused) .task { isFocused = true } } } Running this on MacOS target gives the following on the console: textSelection = nil textSelection = TextSelection(indices: SwiftUI.TextSelection.Indices.selection(Range(0[any]..<0[any])), affinity: SwiftUI.TextSelectionAffinity.downstream) Running the code on iOS gives: textSelection = TextSelection(indices: SwiftUI.TextSelection.Indices.selection(Range(1[any]..<1[any])), affinity: SwiftUI.TextSelectionAffinity.upstream) textSelection = TextSelection(indices: SwiftUI.TextSelection.Indices.selection(Range(1[any]..<1[any])), affinity: SwiftUI.TextSelectionAffinity.upstream) Note here the range is 1..<1 - which is incorrect. Also of side interest this behaviour changes if you remove the axis parameter: textSelection = nil Am I missing something, or is this a bug?
2
0
120
2w
Present User an error message when SwiftData save fails
Have a data model that sets certain fields as unique. If the user attempts to save a duplicate value, the save fails quietly with no indication to the user that the save failed. The program is on Mac OS 26.0.1 @Environment(\.modelContext) var modelContext @Query private var typeOfContracts: [TypeOfContract] @State private var typeName: String = "" @State private var typeCode: String = "" @State private var typeDescription: String = "" @State private var contracts: [Contract] = [] @State private var errorMessage: String? = "Data Entered" @State private var showAlert: Bool = false var body: some View { Form { Text("Enter New Contract Type") .font(.largeTitle) .foregroundStyle(Color(.green)) .multilineTextAlignment(.center) TextField("Contract Type Name", text: $typeName) .frame(width: 800, height: 40) TextField("Contract Type Code", text: $typeCode) .frame(width: 800, height: 40) Text("Contract Type Description") TextEditor(text: $typeDescription) .frame(width: 800, height: 200) .scrollContentBackground(.hidden) .background(Color.teal) .font(.system(size: 24)) Button(action: { self.saveContractType() }) { Text("Save new contract type") } } } func saveContractType() { let typeOfContract = TypeOfContract(contracts: []) typeOfContract.typeName = typeName typeOfContract.typeCode = typeCode typeOfContract.typeDescription = typeDescription modelContext.insert(typeOfContract) do { try modelContext.save() }catch { errorMessage = "Error saving data: \(error.localizedDescription)" } } } I have tried to set alerts but Xcode tells me that the alerts are not in scope
10
0
257
2w
Prevent SwiftUI to stop rendering UI when window loses focus.
Hello, I am writing an audio utility, with a typical audio track player, in SwiftUI for macos 26. My current problem is that the SwiftUI stops rendering the main window UI when the window loses focus. This is a problem since even clicking on the app menu bar has the window loose focus, and the timer, time cursor and all animations of the audio piece stop. All baground services, audio, timers and model continue running (even tho with some crackling on the switch). Once the window focus is re-obtained the animations continue and skip to current state. I have read that SwiftUI optimizes macos like ios, and disables the ui run loop, but there must be a way to disable, since this obviously not the case for most mac app. Is there a solution with either SwiftUI or involving AppKit?
1
0
119
2w
Picker using SwiftData
I am attempting to impliment a a Picker that uses SwiftData to fill in the choices. I am missing something because I can get the picker to appear with the proper selections but the picker does not register my choice (no check mark appears and the text in the picker window is blank after I move to the next field. The model import Foundation import SwiftData //Model one: type of contract, i.e. Firm Fixed Price, etc @Model final class TypeOfContract { var contracts: [Contract] @Attribute(.unique) var typeName: String @Attribute(.unique) var typeCode: String var typeDescription: String init(contracts: [Contract], typeName: String = "", typeCode: String = "", typeDescription: String = "") { self.contracts = contracts self.typeName = typeName self.typeCode = typeCode self.typeDescription = typeDescription } } //Model two: the Contract @Model final class Contract { var contractType: TypeOfContract? var costReports: [CostReport] @Attribute(.unique) var contractNumber: String @Attribute(.unique) var contractName: String var startDate: Date var endDate: Date var contractValue: Decimal var contractCompany: String var contractContact: String var contactEmail: String var contactPhone: String var contractNotes: String init(contractType: TypeOfContract? = nil, costReports: [CostReport], contractNumber: String = "", contractName: String = "", startDate: Date = .now, endDate: Date = .now, contractValue: Decimal = 0.00, contractCompany: String = "", contractContact: String = "", contactEmail: String = "", contactPhone: String = "", contractNotes: String = "") { self.contractType = contractType self.costReports = costReports self.contractNumber = contractNumber self.contractName = contractName self.startDate = startDate self.endDate = endDate self.contractValue = contractValue self.contractCompany = contractCompany self.contractContact = contractContact self.contactEmail = contactEmail self.contactPhone = contactPhone self.contractNotes = contractNotes } } //Model Three: The Cost Reports @Model final class CostReport { var contract: Contract? var periodStartDate: Date var periodEndDate: Date var bCWP: Double //Budgeted Cost Work Performed var aCWP: Double //Actual Cost Work Performed var bCWS: Double //Budgeted Cost Work Scheduled //Calculated fields init(contract: Contract? = nil, periodStartDate: Date = .now, periodEndDate: Date = .now, bCWP: Double = 0.0, aCWP: Double = 0.0, bCWS: Double = 0.0) { self.contract = contract self.periodStartDate = periodStartDate self.periodEndDate = periodEndDate self.bCWP = bCWP self.aCWP = aCWP self.bCWS = bCWS } } The Swift Code for the input form import SwiftData struct EnterNewContract: View { @Environment(\.modelContext) var modelContext @Query(sort: \TypeOfContract.typeCode) private var typeOfContracts: [TypeOfContract] @Query private var contracts: [Contract] @State private var costReports: [CostReport] = [] @State private var contractType: [TypeOfContract] = [] @State private var contractNumber: String = "" @State private var contractName: String = "" @State private var startDate: Date = Date() @State private var endDate: Date = Date() @State private var contractValue: Decimal = 0 @State private var contractCompany: String = "" @State private var contractContact: String = "" @State private var contactEmail: String = "" @State private var contactPhone: String = "" @State private var contractNotes: String = "" var body: some View { Form { VStack { Section(header: Text("Enter New Contract") .foregroundStyle(.green) .font(.headline)){ Picker("Select a type of contract", selection: $contractType) { ForEach(typeOfContracts, id: \.self) { typeOfContracts in Text(typeOfContracts.typeCode) .tag(contractType) } } TextField("Contract Number", text: $contractNumber) .frame(width: 800, height: 40) TextField("Contract Name", text: $contractName) .frame(width: 800, height: 40) DatePicker("Contract Start Date", selection: $startDate, displayedComponents: [.date]) DatePicker("Contract End Date", selection: $endDate, displayedComponents: [.date]) } } } } }
3
0
156
2w