Hi,
I am a new SwiftUI app developer and developing my first application. In the process of designing not very GUI rich app, I noticed my app crashed whenever I switched orientation (testing on multiple iPhone devices).
After going through all kind of logs and errors, performance enhancements nothing worked.
Then I started rolling back all GUI related features 1 by 1 and tested (I am sure there are better approaches, but excuse me I am novice in app development :) ).
Even though it's time consuming, I could pin point the cause of the fatal error and app crash, it's due to multiple .shadow modifiers I used on NavigationLink inside a ForEach look (to be precise I used it like following,
.shadow(radius: 15)
.shadow(radius: 20)
.shadow(radius: 20)
.shadow(radius: 20)
.shadow(radius: 20)
Note, there are only 7 items in List and it uses the Hero View (like app store's Today section) for child views.
Once I got rid of shadow modifies or used only 1 app works fine and doesn't crash.
Lesson learnt...
P.S.
It's so ironic that so performance tuned devices couldn't handle this basic GUI stuff.
SwiftUI
RSS for tagProvide views, controls, and layout structures for declaring your app's user interface using SwiftUI.
Post
Replies
Boosts
Views
Activity
why do I need to set the font of an image of an SF symbol to get the effect to work? This should be a bug, it's bad behavior. Xcode 16.1 iOS 18.1, so frustrating.
for example: this works
Image(systemName: "arrow.trianglehead.2.clockwise.rotate.90.circle.fill")
.symbolEffect(.rotate, options: .repeat(.continuous), value: isActive)
.font(.largeTitle)
.onAppear() {
isActive = true
}
but this does not animate, which makes no sense
Image(systemName: "arrow.trianglehead.2.clockwise.rotate.90.circle.fill")
.symbolEffect(.rotate, options: .repeat(.continuous), value: isActive)
.onAppear() {
isActive = true
}
its the same if you use a simple setup and different font size, and whether font is before or after the symbol effect
Image(systemName: "arrow.trianglehead.2.clockwise.rotate.90.circle.fill")
.font(.headline) // only works if this line is here
.symbolEffect(.rotate, options: .repeat(.continuous))
Hello everyone! I've encountered an issue related to SwiftUI and StoreKit. Please take a look at the SwiftUI code snippet below:
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationStack {
List {
NavigationLink {
Page1()
} label: {
Text("Go to Page 1")
}
}
}
}
}
struct Page1: View {
@Environment(\.dismiss) private var dismiss
@State private var string: String = ""
var body: some View {
List {
NavigationLink {
List {
Page2(string: $string)
.simpleValue(4)
}
} label: {
Text("Tap this button will freeze the app")
}
}
.navigationTitle("Page 1")
}
}
struct Page2: View {
@Binding var string: String?
init(string: Binding<String>) {
self._string = Binding(string)
}
var body: some View {
Text("Page 2")
}
}
extension EnvironmentValues {
@Entry var simpleValue: Int = 3
}
extension View {
func simpleValue(_ value: Int) -> some View {
self.environment(\.simpleValue, value)
}
}
This view runs normally until the following symbol is referenced anywhere in the project:
import StoreKit
extension View {
func notEvenUsed() -> some View {
self.manageSubscriptionsSheet(isPresented: .constant(false))
}
}
It seems that once the project links the View.manageSubscriptionsSheet(isPresented:) method, regardless of whether it's actually used, it causes the above SwiftUI view to freeze.
Steps to Reproduce:
Clone the repository: https://github.com/gongzhang/StrangeFreeze
Open it in Xcode 16 and run on iOS 17-18.1
Navigate to the second page and tap the button, causing the app to freeze.
Remove manageSubscriptionsSheet(...), then everything will work fine
How to reproduce: create blank Xcode project run on physical iPhone(mine 14 pro) not simulator, updated iOS18.1.1 most up to date, on Xcode 16.1 make a text field enter any value in it in console:
Can't find or decode reasons
Failed to get or decode unavailable reasons
This is happening in my other projects as well and I don't know a fix for it is this just an Xcode bug random log noise? It makes clicking the text field lag sometimes on initial tap.
I am working on the device activity report. and fetched data is loading on the chart. I am developing app using TabbarController. when I go to another tab and come back to the chart screen, it disappears.
Here, I am working on a storyboard using Swift language, and device activity reports can be fetched only with SwiftUI. So, the problem is with it? Following the current code.
@State private var context: DeviceActivityReport.Context = .init(rawValue: "Daily Activity")
@State private var report: DeviceActivityReport?
@State private var filter = DeviceActivityFilter(
segment: .daily(
during: Calendar.current.dateInterval(
of: .day, for: .now
)!
)
// users: .all
// devices: .init([.iPhone, .iPad])
)
@State var isReload: Bool = false
var body: some View {
ZStack {
if isReload {
LoadingView(title: "Data is loading...")
} else if let report = report {
report
} else {
DeviceActivityReport(context, filter: filter)
}
}
.onAppear {
DispatchQueue.main.async {
report = DeviceActivityReport(context, filter: filter)
}
}
}
struct LoadingView: View {
var title: String = "Please wait..."
var body: some View {
HStack {
ProgressView(title)
.font(.system(size: 14, weight: .medium))
.progressViewStyle(.horizontal)
.tint(Color(.darkGray))
.padding(8)
}
.background(Color(.white))
.cornerRadius(8)
.clipped()
}
}
I am trying to get my head around how to implement a MapKit view using UIViewRepresentable (I want the map to rotate to align with heading, which Map() can't handle yet to my knowledge). I am also playing with making my LocationManager an Actor and setting up a listener. But when combined with UIViewRepresentable this seems to create a rather convoluted data flow since the @State var of the vm needs to then be passed and bound in the UIViewRepresentable. And the listener having this for await location in await lm.$lastLocation.values seems at least like a code smell. That double await just feels wrong. But I am also new to Swift so perhaps what I have here actually is a good approach?
struct MapScreen: View {
@State private var vm = ViewModel()
var body: some View {
VStack {
MapView(vm: $vm)
}
.task {
vm.startWalk()
}
}
}
extension MapScreen {
@Observable
final class ViewModel {
private var lm = LocationManager()
private var listenerTask: Task<Void, Never>?
var course: Double = 0.0
var location: CLLocation?
func startWalk() {
Task {
await lm.startLocationUpdates()
}
listenerTask = Task {
for await location in await lm.$lastLocation.values {
await MainActor.run {
if let location {
withAnimation {
self.location = location
self.course = location.course
}
}
}
}
}
Logger.map.info("started Walk")
}
}
struct MapView: UIViewRepresentable {
@Binding var vm: ViewModel
func makeCoordinator() -> Coordinator {
Coordinator(parent: self)
}
func makeUIView(context: Context) -> MKMapView {
let view = MKMapView()
view.delegate = context.coordinator
view.preferredConfiguration = MKHybridMapConfiguration()
return view
}
func updateUIView(_ view: MKMapView, context: Context) {
context.coordinator.parent = self
if let coordinate = vm.location?.coordinate {
if view.centerCoordinate != coordinate {
view.centerCoordinate = coordinate
}
}
}
}
class Coordinator: NSObject, MKMapViewDelegate {
var parent: MapView
init(parent: MapView) {
self.parent = parent
}
}
}
actor LocationManager{
private let clManager = CLLocationManager()
private(set) var isAuthorized: Bool = false
private var backgroundActivity: CLBackgroundActivitySession?
private var updateTask: Task<Void, Never>?
@Published var lastLocation: CLLocation?
func startLocationUpdates() {
updateTask = Task {
do {
backgroundActivity = CLBackgroundActivitySession()
let updates = CLLocationUpdate.liveUpdates()
for try await update in updates {
if let location = update.location {
lastLocation = location
}
}
} catch {
Logger.location.error("\(error.localizedDescription)")
}
}
}
func stopLocationUpdates() {
updateTask?.cancel()
updateTask = nil
}
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
switch clManager.authorizationStatus {
case .authorizedAlways, .authorizedWhenInUse:
isAuthorized = true
// clManager.requestLocation() // ??
case .notDetermined:
isAuthorized = false
clManager.requestWhenInUseAuthorization()
case .denied:
isAuthorized = false
Logger.location.error("Access Denied")
case .restricted:
Logger.location.error("Access Restricted")
@unknown default:
let statusString = clManager.authorizationStatus.rawValue
Logger.location.warning("Unknown Access status not handled: \(statusString)")
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
Logger.location.error("\(error.localizedDescription)")
}
}
Adding an Import... menu item using .commands{CommandGroup... on
DocumentGroup(
...
) {
ContentView()
}
.commands {
CommandGroup(replacing: .importExport) {
Button("Import…") {
isImporting = true
}
.keyboardShortcut("I", modifiers: .option)
.fileImporter(
isPresented: $isImporting,
allowedContentTypes: [.commaSeparatedText],
allowsMultipleSelection: false
) { result in
switch result {
case .success(let urls):
print("File import success")
ImportCSV.importCSV(url: urls, in: context) // This is the issue
case .failure(let error):
print("File import error: \(error)")
}
}
}
I could get this to work if I were not using DocumentGroup but instead programmatically creating the modelContext.
using the shared modelContext in ImportCSV is not possible since that is not a View
passing the context as shown above would work if I knew how to get the modelContext but does it even exist yet in Main?
Is this the right place to put the commands code?
Perhaps the best thing is to have a view appear on import, then used the shared modelContext. In Xcode menu File/Add Package Dependencies... opens a popup. How is that done?
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!
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){}
}
}
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
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?
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.
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?
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??
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!
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.
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"
Thanks in advance for your help! after adding the GooglePlaces package dependency, I added 'import GooglePlaces' to my App.Swift file, and content no longer previews. Thoughts?
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.
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.