In iOS 18.4.1, DocumentGroup contains the DocumentView twice. (this may cause issues with alerts)
To reproduce (iOS 18.4):
In XCode Version 16.3 (16E140), create new project. Choose iOS, "Document App". No need to make code changes.
Compile and run app on iOS 18.4 (simulator or device).
in iOS (sim or device): Tap create document (once the app launched).
in XCode: click "Debug View Hierarchy"
in XCode: rotate the view Hierarch to reveal duplicated Document View hierarchies (2 Document Hosting Controllers), see screenshot.
This probably affects alert view... I get warnings and it does not work properly (used to work ok on previous versions).
Previous versions
To compare with previous versions of iOS, run the same code and procedure on iOS 18.3 for example (see screenshot).
Will report on Feedback assistant as well...
SwiftUI
RSS for tagProvide views, controls, and layout structures for declaring your app's user interface using SwiftUI.
Posts under SwiftUI tag
200 Posts
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
For an iOS app that runs in both child and parent mode across iOS devices. On the child device, with Family Controls enabled using .child permissions via AuthorizationCenter.requestAuthorization(for: .child).
Is any way to display a list of recently used apps by the child on the parent (guardian) device, in a privacy-preserving and Apple-compliant way?
I'm experiencing an issue with a SwiftUI document-based app where document files are not appearing in the "Recents" tab or anywhere in the Files app when created from the "Recents" tab. However, when creating documents from the "Browse" tab, they work as expected.
When I print the URL of the created document, it shows a valid path, but when navigating to that path, the file doesn't appear. This seems to be a specific issue related to document creation while in the "Recents" tab.
Steps to Reproduce
Use Apple's demo app for document-based SwiftUI apps: https://developer.apple.com/documentation/swiftui/building-a-document-based-app-with-swiftui
Run the app and navigate to the "Recents" tab in the Files app
Create a new document
Note that the document doesn't appear in "Recents" or anywhere in Files app
Now repeat the process but create the document from the "Browse" tab - document appears correctly
Environment:
Xcode 16.3
iOS 18.4
Expected Behavior:
Documents created while in the "Recents" tab should be saved and visible in the Files app just like when created from the "Browse" tab.
I have a SwiftUI view that I have wrapped using UIHostingController for use within UIKit.
Requirement: Within the UIKit environment, I want to get all the subviews of this SwiftUI view and determine whether the images within those subviews have finished loading.
For UIKit views, we can use view.subviews to get all the subviews and do the check.
However, for SwiftUI views, I found that the view.subviews turns out to be an empty array, making it impossible to do further checks.
So the question is How can I get the subviews of a SwiftUI view?
Hoping someone can help me with this…
The error is… Generic parameter ‘/‘ cannot be inferred.
.multilineTextAlignment(.center)
.onAppear(perform: {
var checkFirstCardLatitude = cards.firstCardLatitude
let charArray = Array(checkFirstCardLatitude)
let allowed: [Character] = ["-", ".", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
for char in charArray {
if char != allowed {
cards.firstCardLatitude = "000.000000" // Reset Text Field
}
}
})
https://github.com/apple/sample-food-truck
Hi! I'm following along with the sample-food-truck application from WWDC 2022. I'm seeing some weird navigation issues when building the app for iPadOS.
The Table component displays a Select Button for selecting elements and a Done Button disabling that state. These buttons seem to be breaking something about navigation on iOS 18.4.1. It's a nondeterministic issue… but tapping the buttons seems to lead to some corrupt state where the app transitions out of OrdersView and back to TruckView.
This code from FoodTruckModel seems to be making a difference:
Task(priority: .background) {
var generator = OrderGenerator.SeededRandomGenerator(seed: 5)
for _ in 0..<20 {
try? await Task.sleep(nanoseconds: .secondsToNanoseconds(.random(in: 3 ... 8, using: &generator)))
Task { @MainActor in
withAnimation(.spring(response: 0.4, dampingFraction: 1)) {
self.orders.append(orderGenerator.generateOrder(number: orders.count + 1, date: .now, generator: &generator))
}
}
}
}
Commenting out that code and disabling the new Order values coming in seems to fix the issue.
Is there any public documentation for me to learn about the Select and Done buttons? I don't see anywhere for me to learn about how these work and what my ability is to customize their behavior.
Any ideas? I can repro from device and simulator.
I added gesture support to my app that supports iOS 16 and 17 and have never had issues with it.
However, when I compiled my app with Xcode 16 I immediately noticed a problem with the app when I ran it in the simulator. I couldn't scroll up or down. I figured out it’s because of my gesture support.
My gesture support is pretty simple.
let myDragGesture = DragGesture()
.onChanged { gesture in
self.offset = gesture.translation
}
.onEnded { _ in
if self.offset.width > threshold {
...some logic
} else if self.offset.width < -threshold {
...some other logic
}
logitUI.debug("drag gesture width was \(self.offset.width)")
self.offset = .zero
}
If I pass nil to .gesture instead of myDragGesture then scrolling starts working again.
Here’s some example output when I’m trying to scroll down. These messages do NOT appear when I run my app on an iOS 16/17 simulator with Xcode 15.
drag gesture width was 5.333328
drag gesture width was -15.333344
drag gesture width was -3.000000
drag gesture width was -24.333328
drag gesture width was -30.666656
I opened FB14205678 about this.
Using the native SwiftUI.Picker to set a @State which is then used to render different child views based on the selected state (using a switch-case inside body) seems to cause those child views to be unresponsive.
The following code below is a replicates the issue. The solution I am currently using is to build my own custom Picker that relies on SwiftUI.Buttons to set the state. This works.
enum PickerSelection: Hashable {
case binding, ownState
}
struct MainApp: View {
@State private var pickerSelection: PickerSelection? = nil
@State private var isToggled: Bool = false
var body: some View {
VStack(alignment: .leading) {
/// Changing `pickerSelection` via `SwiftUI.Picker` causes child views' toggles to be unresponsive.
Picker("Picker", selection: $pickerSelection) {
Text("No Option").tag(Optional<PickerSelection>(nil))
Text("Binding").tag(PickerSelection.binding)
Text("Own state").tag(PickerSelection.ownState)
}
/// Changing `pickerSelection` via a custom `Button`-based picker works as expected.
CustomPickerWithButtonBased(pickerSelection: $pickerSelection)
switch pickerSelection {
case .binding:
ChildViewWithBinding(isToggled: $isToggled)
case .ownState:
ChildViewManagingOwnState()
case .none:
EmptyView()
}
Spacer()
}
.padding()
}
}
struct ChildViewWithBinding: View {
@Binding var isToggled: Bool
var body: some View {
Toggle("ChildViewWithBinding", isOn: $isToggled)
}
}
struct ChildViewManagingOwnState: View {
@State private var isToggled: Bool = false
var body: some View {
Toggle("ChildViewManagingOwnState", isOn: $isToggled)
}
}
struct CustomPickerWithButtonBased: View {
@Binding var pickerSelection: PickerSelection?
var body: some View {
HStack {
Button {
pickerSelection = .binding
} label: {
Text("Binding")
}
Button {
pickerSelection = .ownState
} label: {
Text("OwnState")
}
}
}
}
Am I missing something with Picker?
I am noticing an issue that when .popoverTip() is presented, any tap gesture will only dismiss the tip and will not be passed down.
This means that if tip is applied to a button, tapping the button will only dismiss the tip but will not trigger the action.
Which logically breaks user expectation and defeats the whole point of a popover tip, as user will need to tap twice on the button to activate intended functionality.
Button("Settings", systemImage: "gear") {
// Will not trigger until tip is dismissed and button is tapped again.
showSettings.toggle()
}
.popoverTip(SettingsTip())
"the compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions" ...... it killing me !!!!
Without developer mode, I was able to get Password AutoFill to work in my SwiftUI app with my local Vapor server using ngrok and adding the Associated Domains capability with the value webcredentials:....ngrok-free.app and the respective apple-app-site-association file on my local server in /.well-known/. (works on device, but not in the simulator).
However, if I use the developer mode (webcredentials:....ngrok-free.app?mode=developer) it only works halfway when running from Xcode: I get asked to save the password, but the saved passwords are not picked up, when I try to login again. Neither on device, nor in the simulator. If I remove the ?mode=developer it seems to work as expected.
Is this by design, or am I missing something?
var body: some View {
...
Section(header: Text("Email")) {
TextField("Email", text: $viewModel.credentials.username)
.textContentType(.username)
.autocapitalization(.none)
.keyboardType(.emailAddress)
}
Section(header: Text("Passwort")) {
SecureField("Passwort", text: $viewModel.credentials.password)
.textContentType(.password)
}
...
}
Topic:
Privacy & Security
SubTopic:
General
Tags:
SwiftUI
Universal Links
Authentication Services
Autofill
I'm building a SwiftUI app with a UITextView subclass, and it seems that the software keyboard doesn't trigger the pressesBegan or pressesEnded functions of UITextView. With a hardware keyboard, pressesBegan works as expected, allowing us to intercept key presses in our subclass.
I can't find any documentation about this, or any other forum posts (here or on Stack Overflow) that talk about a discrepancy between software and hardware keyboard behaviors, and I can't believe this is an intended behavior. Our app is a SwiftUI app, in case that's relevant.
Does anyone have any guidance? Is this a bug or am I not understanding this API? Any information or work arounds would be greatly appreciated.
I've made a sample project that demonstrates this issue, which you can grab from GitHub at https://github.com/nyousefi/KeyPressSample. To see this in action, run the sample project and start pressing keys. The hardware keyboard will print the key press at the top of the screen (above the text view), while the software keyboard won't.
I have a TextEditor, to the constructor of which in addition to the text I pass an object of the TextSelection? type. I check on the Simulator with iOS 18.2. An attempt to clear the text leads to a crash with the message "Thread 1: Fatal error: String index is out of bounds" in Xcode.
More about the error:
libswiftCore.dylib`_swift_runtime_on_report:
-> 0x194f32024 <+0>: ret
More about the reproduction conditions:
struct MyView: View {
@Bindable private var viewModel = MyViewModel()
@State var myTextSelection: TextSelection? = nil
var body: some View {
ZStack {
// Some other code
myEditor
// Some other code
}
.toolbar {
ToolbarItem(placement: .primaryAction) {
Button {
viewModel.clear()
} label: {
Label("Clear", systemImage: "eraser")
}
}
}
}
var myEditor: some View {
ZStack(alignment: .topLeading) {
TextEditor(text: $viewModel.text, selection: $myTextSelection)
.disableAutocorrection(true)
.autocapitalization(.sentences)
}
// Some other code
}
}
MyViewModel:
@Observable
final class MyViewModel: ObservableObject {
var text: String = ""
func clear() {
text = ""
}
}
While trying the new ScrollPosition API I noticed that scrollTo(id: anchor:) behaves different than ScrollViewProxy.scrollTo(_: anchor:).
Consider the following example:
struct ContentView: View {
@State private var position = ScrollPosition(edge: .top)
var body: some View {
NavigationStack {
ScrollViewReader { proxy in
ScrollView {
VStack(spacing: 8) {
ForEach(1..<100) { index in
Text(verbatim: index.formatted())
.frame(maxWidth: .infinity)
.background(.gray)
.id(index)
}
}
}
.scrollPosition($position)
.toolbar {
ToolbarItemGroup(placement: .bottomBar) {
Spacer()
Button("50 (T)") {
withAnimation {
position.scrollTo(id: 50, anchor: .top)
// proxy.scrollTo(50, anchor: .top)
}
}
Button("50 (B)") {
withAnimation {
position.scrollTo(id: 50, anchor: .bottom)
// proxy.scrollTo(50, anchor: .bottom)
}
}
Spacer()
}
}
}
}
}
}
The position methods don't align top and bottom edges, but the proxy ones do.
Is this expected or is it a bug?
I have a SwiftUI app. It fetches records through CoreData. And I want to show some records on a widget. I understand that I need to use AppGroup to share data between an app and its associated widget.
import Foundation
import CoreData
import CloudKit
class DataManager {
static let instance = DataManager()
let container: NSPersistentContainer
let context: NSManagedObjectContext
init() {
container = NSPersistentCloudKitContainer(name: "DataMama")
container.persistentStoreDescriptions = [NSPersistentStoreDescription(url: FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: group identifier)!.appendingPathComponent("Trash.sqlite"))]
container.loadPersistentStores(completionHandler: { (description, error) in
if let error = error as NSError? {
print("Unresolved error \(error), \(error.userInfo)")
}
})
context = container.viewContext
context.automaticallyMergesChangesFromParent = true
context.mergePolicy = NSMergePolicy(merge: .mergeByPropertyObjectTrumpMergePolicyType)
}
func save() {
do {
try container.viewContext.save()
print("Saved successfully")
} catch {
print("Error in saving data: \(error.localizedDescription)")
}
}
}
// ViewModel //
import Foundation
import CoreData
import WidgetKit
class ViewModel: ObservableObject {
let manager = DataManager()
@Published var records: [Little] = []
init() {
fetchRecords()
}
func fetchRecords() {
let request = NSFetchRequest<Little>(entityName: "Little")
do {
records = try manager.context.fetch(request)
records.sort { lhs, rhs in
lhs.trashDate! < rhs.trashDate!
}
} catch {
print("Fetch error for DataManager: \(error.localizedDescription)")
}
WidgetCenter.shared.reloadAllTimelines()
}
}
So I have a view model that fetches data for the app as shown above.
Now, my question is how should my widget get data from CoreData? Should the widget get data from CoreData through DataManager? I have read some questions here and also read some articles around the world. This article ( https://dev.classmethod.jp/articles/widget-coredate-introduction/ ) suggests that you let the Widget struct access CoreData through DataManager. If that's a correct fashion, how should the getTimeline function in the TimelineProvider struct get data? This question also suggests the same. Thank you for your reading my question.
In the AVP project, a selector pops up, only wanting to filter spatial videos. When selecting the material of one of the spatial videos, the selection result returns empty. How can we obtain the video selected by the user and get the path and the URL of the file
The code is as follows:
PhotosPicker(selection: $selectedItem, matching: .videos) {
Text("Choose a spatial photo or video")
}
func loadTransferable(from imageSelection: PhotosPickerItem) -> Progress {
return imageSelection.loadTransferable(type: URL.self) { result in
DispatchQueue.main.async {
// guard imageSelection == self.imageSelection else { return }
print("加载成功的图片集合:(result)")
switch result {
case .success(let url?):
self.selectSpatialVideoURL = url
print("获取视频链接:(url)")
case .success(nil):
break
// Handle the success case with an empty value.
case .failure(let error):
print("spatial错误:(error)")
// Handle the failure case with the provided error.
}
}
}
}
In iOS 18, using .highPriorityGesture does not interfere with Button tap detection. However, on iOS 17 and earlier, setting a .highPriorityGesture causes the Button's tap action to stop responding.
I am using .highPriorityGesture in an attempt to support both tap and long-press gestures on a Button, which works as expected in iOS 18. However, the same implementation prevents taps on earlier versions.
Is using .highPriorityGesture on a Button not recommended in this case? Or is this an issue specific to how .highPriorityGesture behaves on iOS 17 and earlier?
Below is a sample code:
struct SampleButton: View {
let title: String
let action: () -> Void
var body: some View {
Button {
NSLog("Tapped")
action()
} label: {
Text(title)
}.highPriorityGesture(LongPressGesture(minimumDuration: 0.5).onEnded { _ in
NSLog("Long press.")
action()
})
}
}
struct ContentView: View {
var body: some View {
VStack {
SampleButton(title: "Tap or LongPress") {}
}
}
}
Environment:
Xcode: Version 16.3 (16E140)
iOS: iOS 18.4(simulator), iOS 17.5, iOS 16.4, iOS 15.2
Looking to start developing at Swift. What is the best way to get started with a job related to Swift development? Is there any specific demanded certification I could pursue?
Thank you.
I noticed that when using .searchable inside a NavigationStack thats inside a TabView, the searchbar briefly overlays the content before disappearing. After that, it is hidden and appears as expected when swiping down.
This only happens when the .searchable is inside the NavigationStack, there is at least one navigationTitle and the NavigationStack is inside a TabView.
Tested on simulator and real device.
I would appreciate any help.
Thanks!
struct FirstScreen: View {
var body: some View {
TabView {
Tab("Tab", systemImage: "heart") {
NavigationStack {
NavigationLink {
SecondScreen()
} label: {
Text("Go to second screen")
}
.navigationTitle("First Screen")
}
}
}
}
}
struct SecondScreen: View {
@State private var text: String = ""
var body: some View {
List {
Text("Some view that extends all the way to the top")
}
.searchable(text: $text)
.navigationTitle("Second Screen")
}
}
Without using a custom preview, you can set .contentShape(RoundedRectangle(cornerRadius: 30)) so that in the "zoomed in" preview of the contextMenu you can have a custom cornerRadius. However, this does not work if you create a custom preview, because then the ContentShape gets applied only to the LIFT PREVIEW, and not to the FINAL PREVIEW state. Heres a sample code - I'd love some support! :)
import SwiftUI
struct ContentView: View {
var body: some View {
VStack {
Rectangle()
.fill(Color.blue)
.frame(width: 300, height: 300)
.cornerRadius(30)
.contentShape(.contextMenuPreview, RoundedRectangle(cornerRadius: 30))
.contextMenu {
Button("Hello") {}
Button("Goofy") {}
} preview: {
Rectangle()
.fill(Color.blue)
.frame(width: 300, height: 300)
.cornerRadius(30)
//.contentShape(RoundedRectangle(cornerRadius: 30))
//.contentShape(.contextMenuPreview, RoundedRectangle(cornerRadius: 30))
}
Text("contextMenu item with large cornerRadius is not working as expected... No way to set contentShape to custom corner radius for final preview - not the lift preview")
}
}
}