There are two issues about SFSafariViewController.
After rotate from landscape to portrait,
The topAnchor is destroyed.
The specified bar tint color and control tint color are invalidated.(Returns to system color)
Regarding the second issue, I’ve found a temporary workaround.
Override the viewWillTransition(to:with:) and keep it empty. Don't call super.viewWillTransition(to:with:).
Since UIKit is not open source, I don’t know the exact cause, but I found something that could be the key to the issue. So, I reported it to Apple Feedback Assistant. You can check the details and the sample project in the GitHub repository below.
https://github.com/ueunli/SafariViewer
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.
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
When a large number of NavigationLinks is within a LazyVStack (or LazyVGrid), ressource usage gets higher (and stays high) the further a user scrolls down.
A simple example to reproduce this:
NavigationStack {
ScrollView {
LazyVStack {
ForEach(0..<5000) { number in
NavigationLink(value: number) {
Text("Number \(number)")
}
}
}
}
.navigationDestination(for: Int.self) { number in
Text("Details for number \(number)")
}
}
List does not exhibit this behavior but is not suitable for my use case.
I am working on a SwiftUI project where I need to dynamically update the UI by adding or removing components based on some event. The challenge is handling complex UI structures efficiently while ensuring smooth animations and state management.
Example Scenario:
I have a screen displaying a list of items.
When a user taps an item, additional details (like a subview or expanded section) should appear dynamically.
If the user taps again, the additional content should disappear.
The UI should animate these changes smoothly without causing unnecessary re-renders.
My Current Approach:
I have tried using @State and if conditions to toggle views, like this:
struct ContentView: View {
@State private var showDetails = false
var body: some View {
VStack {
Button("Toggle Details") {
showDetails.toggle()
}
if showDetails {
Text("Additional Information")
.transition(.slide) // Using animation
}
}
.animation(.easeInOut, value: showDetails)
}
}
However, in complex UI scenarios where multiple components need to be shown/hidden dynamically, this approach is not maintainable and could cause performance issues. I need help with the below questions.
Questions:
State Management: Should I use @State, @Binding, or @ObservedObject for handling dynamic UI updates efficiently?
Best Practices: What are the best practices for structuring SwiftUI views to handle dynamic updates without excessive re-renders?
Performance Optimization: How can I prevent unnecessary recomputations when updating only specific UI sections?
Animations & Transitions: What is the best way to apply animations smoothly while toggling visibility of multiple components?
Advanced Approaches: Are there better techniques using @EnvironmentObject, ViewBuilder, or even GeometryReader for dynamically adjusting UI layouts?
Any insights, code examples, or resources would be greatly appreciated.
I encountered an issue with UITextView on iOS 18 where, when typing Pinyin, extra Unicode characters such as U+2004 are inserted unexpectedly. This occurs when using a Chinese input method.
Steps to Reproduce:
1. Set up a UITextView with a standard delegate implementation.
2. Use a Pinyin input method to type the character “ㄨ”.
3. Observe that after the character “ㄨ” is typed, extra spaces (U+2004) are inserted automatically between the characters.
Code Example:
class ViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
extension ViewController: UITextViewDelegate {
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
print("shouldChangeTextIn: range \(range)")
print("shouldChangeTextIn: replacementText \(text)")
return true
}
func textViewDidChange(_ textView: UITextView) {
let currentText = textView.text ?? ""
let unicodeValues = currentText.unicodeScalars.map { String(format: "U+%04X", $0.value) }.joined(separator: " ")
print("textViewDidChange: textView.text: \(currentText)")
print("textViewDidChange: Unicode Scalars: \(unicodeValues)")
}
}
Output:
shouldChangeTextIn: range {0, 0}
shouldChangeTextIn: replacementText ㄨ
textViewDidChange: textView.text: ㄨ
textViewDidChange: Unicode Scalars: U+3128
------------------------
shouldChangeTextIn: range {1, 0}
shouldChangeTextIn: replacementText ㄨ
textViewDidChange: textView.text: ㄨ ㄨ
textViewDidChange: Unicode Scalars: U+3128 U+2004 U+3128
------------------------
shouldChangeTextIn: range {3, 0}
shouldChangeTextIn: replacementText ㄨ
textViewDidChange: textView.text: ㄨ ㄨ ㄨ
textViewDidChange: Unicode Scalars: U+3128 U+2004 U+3128 U+2004 U+3128
This issue may affect text processing, especially in cases where precise text manipulation is required, such as calculating ranges in shouldChangeTextIn.
I'm trying to test migration between schemas but I cannot get it to work properly. I've never been able to get a complex migration to work properly unfortunately. I've removed a property and added 2 new ones to one of my data models.
This is my current plan.
enum MigrationV1toV2: SchemaMigrationPlan {
static var schemas: [any VersionedSchema.Type] {
[SchemaV1.self, SchemaV2.self]
}
static let migrateV1toV2 = MigrationStage.custom(
fromVersion: SchemaV1.self,
toVersion: SchemaV2.self,
willMigrate: { context in
print("Inside will migrate")
// Get old months
let oldMonths = try context.fetch(FetchDescriptor<SchemaV1.Month>())
print("Number of old months:\(oldMonths.count)")
for oldMonth in oldMonths {
// Convert to new month
let newMonth = Month(name: oldMonth.name, year: oldMonth.year, limit: oldMonth.limit)
print("Number of transactions in oldMonth: \(oldMonth.transactions?.count)")
print("Number of transactions in newMonth: \(newMonth.transactions?.count)")
// Convert transactions
for transaction in oldMonth.transactions ?? [] {
// Set action and direction
let action = getAction(from: transaction)
let direction = getDirection(from: transaction)
// Update category if necessary
var category: TransactionCategory? = nil
if let oldCategory = transaction.category {
category = TransactionCategory(
name: oldCategory.name,
color: SchemaV2.Category.Colors.init(rawValue: oldCategory.color?.rawValue ?? "") ?? .blue,
icon: getCategoryIcon(oldIcon: oldCategory.icon)
)
// Remove old category
context.delete(oldCategory)
}
// Create new
let new = Transaction(
date: transaction.date,
action: action,
direction: direction,
amount: transaction.amount,
note: transaction.note,
category: category,
month: newMonth
)
// Remove old transaction from month
oldMonth.transactions?.removeAll(where: { $0.id == transaction.id })
// Delete transaction from context
context.delete(transaction)
// Add new transaction to new month
newMonth.transactions?.append(new)
}
// Remove old month
context.delete(oldMonth)
print("After looping through transactions and deleting old month")
print("Number of transactions in oldMonth: \(oldMonth.transactions?.count)")
print("Number of transactions in newMonth: \(newMonth.transactions?.count)")
// Insert new month
context.insert(newMonth)
print("Inserted new month into context")
}
// Save
try context.save()
}, didMigrate: { context in
print("In did migrate")
let newMonths = try context.fetch(FetchDescriptor<SchemaV2.Month>())
print("Number of new months after migration: \(newMonths.count)")
}
)
static var stages: [MigrationStage] {
[migrateV1toV2]
}
}
It seems to run fine until it gets the the line: try context.save(). At this point it fails with the following line:
SwiftData/PersistentModel.swift:726: Fatal error: What kind of backing data is this? SwiftData._KKMDBackingData<Monthly.SchemaV1.Transaction>
Anyone know what I can do about this?
I've been trying to add a header to the tabSection of the tabview in tvos 18+ .
init(
@TabContentBuilder<SelectionValue> content: () -> Content,
@ViewBuilder header: () -> Header
) where Header : View, Footer == EmptyView
Here the ehader clearly conforms to View but i cant quite fit the label with uiimage as the icon into this. This Label when i add it to any other view, the image is in the specified 50 x 50 size but inside header it functions weirdly to be of a huge size. but also to note, if i simply hav an icon here, it is correct. So what is the problem here.. can someone help me? im supposed to add the user profile and name in the header. I dont think there's any other way
I plan to use the entire screen height minus 40 pixels approximately to not overlap with the time, batter and carrier data. However, I noticed that in the code shared below the vstack with pink background is not displayed at the top of the screen. The interesting part is that it's actually occupying an offset at the top of the screen. What's more, when I set an offset greater than 70 pixels, then the pink vstack displays on the view! Thus, I'm looking for an explanation to this swiftui rendering issue.
Offset less than 70 pixels:
Offset greater or equal than 70 pixels:
GeometryReader { proxy in
let offset = 40.0
let height = proxy.size.height - offset
ZStack {
VStack(spacing:0){
VStack{Text("heasdas")}.frame(width: 300,height: offset,alignment: .leading)
.background(.pink)
VStack {
HStack(alignment:.center,spacing:10){
Text("Shapecloud")
.font(.callout)
.fontWeight(.semibold)
.frame(alignment: .leading)
SLine()
}
.frame(maxWidth: .infinity,alignment: .leading)
Text("Digital Twin Solutions\nServices")
.font(.largeTitle)
.fontWeight(.medium)
.frame(maxWidth: .infinity,alignment: .leading)
}
.frame(maxWidth: .infinity,maxHeight: 0.3*height,alignment: .top)
.background(.red)
VStack {
VideoPlayer(player: player)
.frame(maxWidth: .infinity,maxHeight: 300)
}
.frame(maxWidth: .infinity,maxHeight: 0.4*height)
.background(.yellow)
VStack{
Button {
} label: {
Text("Subscribe now").foregroundStyle(.black)
.font(.headline)
.fontWeight(.semibold)
}
.frame(maxWidth: .infinity,maxHeight: 50)
.border(Color.black, width: 2)
Button {
} label: {
Text("Sign In").foregroundStyle(.white)
.font(.headline)
}
.frame(maxWidth: .infinity,maxHeight: 50)
.background(Color.theme.primary)
}
.frame(maxWidth: .infinity,maxHeight: 0.3*height)
.background(.green)
}
.padding(.horizontal, 32)
.background(.cyan)
.ignoresSafeArea(.all)
}
.ignoresSafeArea(.all)
}
.ignoresSafeArea(.all)
I recently detected a special crash on 18.0, 18.1, 18.1.1, 18.2,18.3 which cannot be repeated, and the page logs are related to the keyboard, is there any idea to deal with this problem?
Exception Category: nsexception
Exception Type: EXC_CRASH (SIGABRT)
Exception Codes: 0x00000000 at 0x0000000000000000
Crashed Thread: 0
CrashDoctor Diagnosis: Application threw exception NSInternalInconsistencyException: Multi layer delegate table missing.
Thread 0 Crashed:
0 CoreFoundation 0x00000001869d87cc __exceptionPreprocess + [ : 164]
1 libobjc.A.dylib 0x0000000183cab2e4 objc_exception_throw + [ : 88]
2 Foundation 0x0000000185da88d8 _userInfoForFileAndLine
3 UIKitCore 0x0000000189e78074 -[UIView _multiLayerDelegatesTableCreateIfNecessary:] + [ : 208]
4 UIKitCore 0x0000000189e780c4 -[UIView _registerMultiLayerDelegate:] + [ : 36]
5 UIKitCore 0x00000001894874c0 -[_UIPortalView setSourceView:] + [ : 132]
6 UIKitCore 0x000000018a1eb6bc -[_UIPortalView initWithSourceView:] + [ : 68]
7 UIKitCore 0x000000018a213ea4 -[_UITextMagnifiedLoupeView initWithSourceView:] + [ : 444]
8 UIKitCore 0x000000018a6c461c +[UITextLoupeSession _makeLoupeViewForSourceView:selectionWidget:orientation:] + [ : 84]
9 UIKitCore 0x000000018a6c47bc +[UITextLoupeSession _beginLoupeSessionAtPoint:fromSelectionWidgetView:inView:orientation:] + [ : 304]
10 UIKitCore 0x0000000189d50ce0 -[UITextRefinementTouchBehavior textLoupeInteraction:gestureChangedWithState:location:translation:velocity:modifierFlags:shouldCancel:] + [ : 1756]
11 UIKit 0x0000000240e309e0 -[UITextRefinementTouchBehaviorAccessibility textLoupeInteraction:gestureChangedWithState:location:translation:velocity:modifierFlags:shouldCancel:] + [ : 216]
12 UIKitCore 0x000000018a4d45b4 -[UITextRefinementInteraction loupeGestureWithState:location:translation:velocity:modifierFlags:shouldCancel:] + [ : 124]
13 UIKitCore 0x000000018a4d3f74 -[UITextRefinementInteraction loupeGesture:] + [ : 548]
14 UIKitCore 0x000000018952eac4 -[UIGestureRecognizerTarget _sendActionWithGestureRecognizer:] + [ : 128]
15 UIKitCore 0x000000018952e934 _UIGestureRecognizerSendTargetActions + [ : 92]
16 UIKitCore 0x000000018952e6f4 _UIGestureRecognizerSendActions + [ : 284]
17 UIKitCore 0x00000001891e1b28 -[UIGestureRecognizer _updateGestureForActiveEvents] + [ : 572]
18 UIKitCore 0x00000001891b3724 _UIGestureEnvironmentUpdate + [ : 2488]
19 CoreFoundation 0x000000018697a1f4 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + [ : 36]
20 CoreFoundation 0x0000000186979f98 __CFRunLoopDoObservers + [ : 552]
21 CoreFoundation 0x00000001869a9028 __CFRunLoopRun + [ : 948]
22 CoreFoundation 0x00000001869a8830 CFRunLoopRunSpecific + [ : 588]
23 GraphicsServices 0x00000001d29881c4 GSEventRunModal + [ : 164]
24 UIKitCore 0x000000018950eeb0 -[UIApplication _run] + [ : 816]
25 UIKitCore 0x00000001895bd5b4 UIApplicationMain + [ : 340]
26 顺丰小哥 0x0000000104423cc0 main + [main.m : 13]
27 (null) 0x00000001ac396ec8 0x0 + 7184412360
Topic:
UI Frameworks
SubTopic:
UIKit
I must admit my knowledge of swift is limited, and I cannot wrap my head around this problem.
I've defined this protocol, so I can use different auth providers in my app.
protocol AuthRepository {
associatedtype AuthData
associatedtype AuthResponseData
associatedtype RegistrationData
associatedtype RegistrationResponseData
func login(with data: AuthData) async throws -> AuthResponseData?
func register(with data: RegistrationData) async throws -> RegistrationResponseData?
}
and an implementation for my server
struct MyServerAuthData {
let email: String
let password: String
}
struct MyServerAuthResponseData {
let token: String
}
struct MyServerRegistrationData {
let email: String
let password: String
let name: String
}
actor AuthRepositoryImpl: AuthRepository {
func login(with data: MyServerAuthData) async throws -> MyServerAuthResponseData? {
...
}
func register(with data: MyServerRegistrationData) async throws -> Void? {
...
}
}
To use across the app, I've created this ViewModel
@MainActor
final class AuthViewModel<T: AuthRepository>: ObservableObject {
private let repository: T
init(repository: T) {
self.repository = repository
}
func login(data: T.AuthData) async throws -> T.AuthResponseData? {
try await repository.login(with: data)
}
func register(with data: T.RegistrationData) async throws {
try await repository.register(with: data)
}
}
defined in the app as
@main
struct MyApp: App {
@StateObject var authViewModel = AuthViewModel(repository: AuthRepositoryImpl())
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(self.authViewModel)
}
}
}
and consumed as
@EnvironmentObject private var authViewModel: AuthViewModel<AuthRepositoryImpl>
But with this code, the whole concept of having a generic implementation for the auth repository is useless, because changing the AuthRepostory will need to search and replace AuthViewModel<AuthRepositoryImpl> across all the app.
I've experienced this directly creating a MockAuthImpl to use with #Preview, and the preview crashed because it defines AuthViewModel(repository: MockAuthImpl()) but the view expects AuthViewModel.
There is a better way to do that?
Hi everyone, im in the process of delving more into coregraphics with swiftui, but I am at a roadblock.
First I would like to ask, what are some good resources to learn coregraphics?
Secondly:
I currently have a circle view made and what I want to do is to make my circle view modular so that it can be directly connected to another given circle by a line. How can I do this?
For example, I want my circles to represent nodes and be able to connect by lines to other nodes that are related.
Thanks in advanced.
Here is my code for the circle view:
@State private var circleProgress: CGFloat = 0
let timer = Timer.publish(every: 0.016, on: .main, in: .common).autoconnect()
private let animationDuration: TimeInterval = 1.5
@Binding var startPoint: CGPoint
@Binding var endPoint: CGPoint
var body: some View {
GeometryReader { geometry in
Canvas { context, size in
// Circle parameters
let circleSize: CGFloat = 50
let circleOrigin = CGPoint(
x: size.width / 4,
y: size.height / 2 - circleSize / 2
)
let circleRect = CGRect(
origin: circleOrigin,
size: CGSize(width: circleSize, height: circleSize)
)
let circleCenter = CGPoint(
x: circleOrigin.x + circleSize / 2,
y: circleOrigin.y + circleSize / 2
)
// Animate circle creation
var circlePath = Path()
circlePath.addArc(
center: circleCenter,
radius: circleSize / 2,
startAngle: .degrees(0),
endAngle: .degrees(360 * circleProgress),
clockwise: false
)
context.addFilter(.shadow(color: .white.opacity(0.6), radius: 5, x: 1, y: 1)) // Add white shadow
context.stroke(
circlePath,
with: .linearGradient(
Gradient(colors: [.purple, .white]),
startPoint: circleRect.origin,
endPoint: CGPoint(x: circleRect.maxX, y: circleRect.maxY)
),
lineWidth: 5
)
}
.frame(width: 300, height: 150)
.onReceive(timer) { _ in
// Update circle progress
let progressChange = 0.02 / animationDuration
if circleProgress < 1.0 {
circleProgress = min(circleProgress + progressChange, 1.0)
} else {
circleProgress = 0.0 // Reset the circle to repeat the animation
}
// Get the starting and ending points of the Canvas view
startPoint = CGPoint(x: geometry.frame(in: .global).minX, y: geometry.frame(in: .global).minY)
endPoint = CGPoint(x: geometry.frame(in: .global).maxX, y: geometry.frame(in: .global).maxY)
// Print the points for debugging
print("Start Point: \(startPoint.x), \(startPoint.y)")
print("End Point: \(endPoint.x), \(endPoint.y)")
}
}
.frame(width: 300, height: 150)
}
}
We have a IOS app and we are using the same app for Mac Catalyst.
In IOS we are able to detect when user take the screenshot using UIApplicationUserDidTakeScreenshotNotification. But in MACCatalyst it is not working.
As per docs UIApplicationUserDidTakeScreenshotNotification and UIScreenCapturedDidChangeNotification are both supported for MacCatalyst 13.1+. But I am not getting screen shot notifications using both
I have a swiftui view with Button(intent: ) and using UIHostingViewcontroller to use it in UIKit. The problem is that button not works in uikit but normal button(without intent works)
Could anyone give some insights to identify the root cause for this crash?
Fatal Exception: NSInternalInconsistencyException
Layout requested for visible navigation bar, <UINavigationBar: 0x120e74280; frame = (0 0; 430 56); autoresize = W; tintColor = <UIDynamicProviderColor: 0x300488b20; provider = <__NSMallocBlock__: 0x300a60900>>; layer = <CALayer: 0x3000f0380>> delegate=0x1277a4600 standardAppearance=0x302d5c770 scrollEdgeAppearance=0x302d5d500, when the top item belongs to a different navigation bar. topItem = <UINavigationItem: 0x10a7d8500> title='Transfers' style=navigator leftBarButtonItems=0x300690020 rightBarButtonItems=0x300613ff0, navigation bar = <UINavigationBar: 0x11a8ef200; frame = (0 0; 430 44); opaque = NO; autoresize = W; layer = <CALayer: 0x3002a44c0>> delegate=0x1277a0c00, possibly from a client attempt to nest wrapped navigation controllers.
====
Fatal Exception: NSInternalInconsistencyException
0 CoreFoundation 0x827cc __exceptionPreprocess
1 libobjc.A.dylib 0x172e4 objc_exception_throw
2 Foundation 0x80f8d8 _userInfoForFileAndLine
3 UIKitCore 0x2b63e8 -[UINavigationBar layoutSubviews]
4 UIKitCore 0xd688 -[UIView(CALayerDelegate) layoutSublayersOfLayer:]
5 UIKitCore 0x14dc14 -[UINavigationBar layoutSublayersOfLayer:]
6 QuartzCore 0x78c28 CA::Layer::layout_if_needed(CA::Transaction*)
7 QuartzCore 0x787b4 CA::Layer::layout_and_display_if_needed(CA::Transaction*)
8 QuartzCore 0xcf914 CA::Context::commit_transaction(CA::Transaction*, double, double*)
9 QuartzCore 0x4e7c4 CA::Transaction::commit()
10 QuartzCore 0x91a0c CA::Transaction::flush_as_runloop_observer(bool)
11 UIKitCore 0xa3568 _UIApplicationFlushCATransaction
12 UIKitCore 0xa0b64 __setupUpdateSequence_block_invoke_2
13 UIKitCore 0xa09d8 _UIUpdateSequenceRun
14 UIKitCore 0xa0628 schedulerStepScheduledMainSection
15 UIKitCore 0xa159c runloopSourceCallback
16 CoreFoundation 0x56328 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__
17 CoreFoundation 0x562bc __CFRunLoopDoSource0
18 CoreFoundation 0x53dc0 __CFRunLoopDoSources0
19 CoreFoundation 0x52fbc __CFRunLoopRun
20 CoreFoundation 0x52830 CFRunLoopRunSpecific
21 GraphicsServices 0x11c4 GSEventRunModal
22 UIKitCore 0x3d2eb0 -[UIApplication _run]
23 UIKitCore 0x4815b4 UIApplicationMain
24 XX 0xa0f64 main + 7 (main.m:7)
25 ??? 0x1abb6eec8 (Missing)
I am working on a React Native application where I want to modify the native text selection menu (the menu that appears when you long-press on text). Specifically, I want to add a custom option alongside the default ones like Copy, Look Up, Translate, Search Web, and Share.
Is there a way to modify the native text selection menu inside a WebView on iOS?
How can I add a custom menu option to the default text selection menu while keeping all the default options intact?
Hello!
I discovered a bug on Catalyst about a three years ago but it still seems to be not fixed. My bug report number is FB9705748.
The Internet is silent on this so I'm even not sure, perhaps it's only me.
So to the problem. When you display UICollectionViewController or UIViewController that contains UICollectionView, interact with the collection view then dismiss the view controller, the displayed view controller isn't released if dismissal is done through navigation bar item.
The problem occurs only when the run target is My Mac (Mac Catalyst). Everything is fine when you run on iOS or via My Mac (Designed for iPad).
The sample project is uploaded to GitHub. It has a video that shows this strange behavior, see the log for 'deinit' messages.
I did have some workaround to fix this but it stops to work, presumable on the new macOS. Also, chances are that it's not only UICollectionView which initiates the glitch, it's just that I only encounter it with collection views.
SwiftUI Issues on iOS 16: App Freezes, Buttons Unresponsive, and Missing Data (Works Fine on iOS 17)
Hi everyone,
I’m experiencing significant issues with my SwiftUI app when running on iOS 16. These issues are not present in iOS 17, where everything works as expected. I’m hoping someone can provide insights or suggestions on how to address these problems.
The Problems
App Freezing:
In certain views, the app becomes completely unresponsive when running on iOS 16.
There are no clear patterns or console logs pointing to the source of the freeze.
Unresponsive Buttons:
Buttons stop working in some views. Tapping them does nothing, even though the logic and bindings are correct.
Missing Data:
Data fetched from services (remote APIs) or local storage doesn’t show up in the UI.
Expected Behavior
The app should handle user interactions and display data correctly on both iOS 16 and iOS 17, without freezes or unresponsive elements.
Environment:
Xcode Version: Xcode 15.4
Deployment Target: iOS 16
Testing Devices: iPhone 14 with iOS 17.6.1, iPhone 13 with iOS 18.1.1, iPhone 8 with iOS 16.4, iPhone 12 with 16.4, iPhone 8 Plus with iOS 16.0, iPhone 8 Plus with 16.7.10
Topic:
UI Frameworks
SubTopic:
SwiftUI
Hey there, I'm new to Swift and currently building my first app. I'm having the error "Extra trailing closure passed in call" in a section and already compared it to working sections and just can't find the error in my code. Maybe you guys can help me:
Form {
Section("Essential Information") {
TextField("Title", text: $title)
TextField("Composer", text: $composer)
TextField("Opus", text: $opus)
}
The error is occurring in the section line.
There are over sections that work perfectly fine:
Section("Additional Details") {
TextField("Epoch", text: $epoch)
TextField("Type", text: $type)
TextField("Accompaniment", text: $accompaniment)
TextField("Length (minutes)", value: $length, format: .number)
.keyboardType(.numberPad)
TextField("Key", text: $key)
TextField("Difficulty", text: $difficulty)
TextField("Tempo (BPM)", value: $tempo, format: .number)
.keyboardType(.numberPad)
}
Topic:
UI Frameworks
SubTopic:
SwiftUI
I don't know why, but for my MacCatalyst target, I have to make my view controller Y orgin 36 and the subtract the view height by 36 points, or the view is clipped.
The following works in my main UIViewController, but feels super hacky. I'd feel better if I understood the issue and addressed it properly.
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
#if targetEnvironment(macCatalyst)
if view.frame.origin.y < 1 {
let f = UIApplication.shared.sceneBounds
let newFrame = CGRect(x: 0.0, y: 36, width: f.size.width, height: f.size.height - 36)
self.view.frame = newFrame
}
#endif
}
My guess is it starts the view under the title bar, but I have these set in the view controller:
self.extendedLayoutIncludesOpaqueBars = false
self.edgesForExtendedLayout = []
I'm working on a SwiftUI based application for MacOS. I have a TabView component with two child Tab components. These Tab components display a List, each derived from an array of elements.
While the application is running, clicking on the tabs in the TabView should switch between the views of different Lists. What I'm experiencing is that switching between the tabs causes a FAULT. With errors:
Row index 1 out of row range (numberOfRows: 1) for <SwiftUI.SwiftUIOutlineListView: 0x1299d2000>
Followed by:
(
0 CoreFoundation 0x000000019e096e80 __exceptionPreprocess + 176
1 libobjc.A.dylib 0x000000019db7ecd8 objc_exception_throw + 88
2 AppKit 0x00000001a1c744e8 -[NSTableRowData _availableRowViewWhileUpdatingAtRow:] + 0
3 SwiftUI 0x00000001cd8953f4 $s7SwiftUI0A17UIOutlineListViewC11removeItems2at8inParent13withAnimationy10Foundation8IndexSetV_ypSgSo07NSTableeL7OptionsVtF + 1232
...
...
)
And finally:
FAULT: NSTableViewException: Row index 1 out of row range (numberOfRows: 1) for <SwiftUI.SwiftUIOutlineListView: 0x1299d2000>; (user info absent)
This error happens when switching between the two tabs, defined thusly:
@main
struct MyApp: App {
@State var rootDirectory: URL
@State var selectedItem: URL
@State var projectNavItems: [NavigationItem] = []
@State var jotNavItems: [NavigationItem] = []
@State var importerIsPresented: Bool = false
let fileManager = FileManager.default
init() {
rootDirectory = URL(string: FileManager.default.currentDirectoryPath)!
selectedItem = URL(string: FileManager.default.currentDirectoryPath)!.appendingPathComponent("README.md")
}
var body: some Scene {
WindowGroup {
NavigationSplitView {
TabView {
Tab("Projects", systemImage: "tray.and.arrow.down.fill") {
List(projectNavItems, selection: $selectedItem) {
// Changing this NavigationLink line to Text($0.title) makes no difference
NavigationLink($0.title, value: $0.id)
}
}
Tab("Jots", systemImage: "tray.and.arrow.up.fill") {
List(jotNavItems, selection: $selectedJot) {
// Can be written as Text($0.title) with no change in behavior
NavigationLink($0.title, value: $0.id)
}
}
}
} detail: {
Editor(for: selectedItem)
}
.fileImporter(
isPresented: $importerIsPresented,
allowedContentTypes: [UTType.folder],
allowsMultipleSelection: false
) { result in
// Code that gets a security scoped resource and populates the
// projectNavItems: [NavItem] and jotNavItems: [NavItem]
// arrays
}
}
.commands(content: {
CommandGroup (before: .newItem) {
Button("Open Journal...") {
importerIsPresented.toggle()
}
}
})
}
}
The error only happens when both Tab views are populated by a List. If the Tab view have different child components, say a List, and a ForEach of Text components, switching between the tabs doesn't produce this error. List views with Text child components also produce this error.
Here are screenshots of the running application
Once the user selects a directory, we see the first Tab > List component populated by contents from the projectNavItems array:
Clicking on the 'Jots' tab switches to the appropriate tab and correctly lists the items in the jotNavItems array, except there are additional lines, seemingly showing that there's an issue.
Clicking back on the 'Projects' tab switches back, but now the List shows only one of the items from the projectNavItems array.
Finally, clicking on 'Jots' again causes the errors to print in the console and interactivity with the tab components ceases. Last screenshot is representative of this state as the application FAULTS.
This seems like a bug in SwifUI, wondering what workarounds I might be able to implement.
I can provide the full backtrace, I cropped it for content length.
I have to decrease main window screen size when user open Immersive space in my project.
Using frame i try it but it not updated main window size it just update view frame.