.onReceive construction isn't working with button long press gesture but tap is working, it increases count by 1. Construction should increase count every 0.5 seconds if button pressed
struct Test: View {
@State private var count = 0
@State private var isLongPressed = false
var body: some View {
VStack {
Text("Count: \(count)")
Button("Increase") {
count += 1
print("Button tapped")
}
.onLongPressGesture {
isLongPressed = true
print("Long press started")
}
.onLongPressGesture(minimumDuration: 0) {
isLongPressed = false
print("Long press ended")
}
}
.onReceive(Timer.publish(every: 0.5, on: .main, in: .common).autoconnect()) { _ in
if isLongPressed {
count += 1
print("Count increased: \(count)")
}
}
}
}
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
Hi,
I have a form on an iPad App I'm developing and the form have text field at its bottom when tapping on it the keyboard cover those text fields how to solve this issue leave a hug gap at bottom of the form so text field jump to top when keyboard shows ?
Kind Regards
the problem I have been having for a few days is that when I want to work with swifui, I open a new swiftui file and preview does not occur, I read it from chatgpt deepsek and many forum sites, is it a systemic failure, please help me, I am having trouble previewing.
Topic:
UI Frameworks
SubTopic:
SwiftUI
I am implementing a new Intents UI Extension and am noticing that the viewWillDisappear, viewDidDisappear, and deinit methods are not being called on my UIViewController that implements INUIHostedViewControlling, when pressing the "Done" button and dismissing the UIViewController.
This causes the memory for the UI Extension to slowly increase each time I re-run the UI Extension until it reaches the 120MB limit and crashes.
Any ideas as to what's going on here and how to solve this issue?
Hi guys, I’m making a simple note taking app and I want to support markdown functionality. I have tried to find libraries and many other GitHub repos but some of them are slow and some of them are very hard to implement and not very customizable.
In WWDC 22 apple also made a markdown to html document app and I also looked at that code and it was awesome. It was fast and reliable (Apple btw).
But the only problem I am facing is that the markdown text is on the left side and the output format is on the right in the form of html. I don’t want that I want both in the same line. In bear notes and things 3 you can write in markdown and you can see that it is converting in the same line. I have also attached example videos. So, I have markdown parser by apple but the only thing in the way is that it is converting it into a html document. Please help me with this. Also please look into the things 3 video they have also completely customized the text attributes selection menu. By default with UITextView we can only enable text attributes and it shows like this.
By clicking more we get the complete formatting menu but not the slider menu which is more convenient. Please also help me this. I don’t know if I can provide apple file but it is from wwdc 22 supporting desktop class interaction
in ios it is not same as it in computer
there is text:"ยินดี
in computer is
but in ios it is
the fontsize is 16
I tried every font which is in ios and tried copy simsun in windows to ios and create CTFont
I draw it using UIGraphics drawString
Hey everyone!
I’m encountering an issue while attempting to animate height changes of the content inside safeAreaInset(edge:alignment:spacing:content:).
When animating a reduction in the frame height, the container view (in my case, Map) also animates unexpectedly.
However, when animating an increase in the frame height, the animation works smoothly, and the Map view remains still.
How can I address this odd resizing behavior of the container?
Code:
struct MapView: View {
var body: some View {
Map()
.safeAreaInset(edge: .bottom) {
MapDetailView()
}
}
}
struct MapDetailView: View {
@State private var oldHeightOffset: CGFloat = 0
@State private var newHeightOffset: CGFloat = 0
@State private var containerHeight: CGFloat = 0
private var drag: some Gesture {
DragGesture(coordinateSpace: .global)
.onChanged { value in
withAnimation(.interactiveSpring) {
newHeightOffset = oldHeightOffset + value.translation.height
}
}
.onEnded { value in
switch newHeightOffset {
case containerHeight * 0.625...containerHeight:
withAnimation(.spring) {
newHeightOffset = containerHeight * 0.75
}
case containerHeight * 0.25..<containerHeight * 0.625:
withAnimation(.spring) {
newHeightOffset = containerHeight * 0.5
}
case 0..<containerHeight * 0.25:
withAnimation(.spring) {
newHeightOffset = 0
}
default:
break
}
oldHeightOffset = newHeightOffset
}
}
var body: some View {
NavigationStack {
Rectangle()
.fill(.clear)
.containerBackground(.ultraThinMaterial, for: .navigation)
}
.gesture(drag)
.containerRelativeFrame(.vertical) { length, _ in
length - newHeightOffset
}
.onGeometryChange(for: CGFloat.self) { geometryProxy in
let frame = geometryProxy.frame(in: .local)
return frame.height + newHeightOffset
} action: { containerHeight in
self.containerHeight = containerHeight
}
}
}
Reducing safe area inset's content height (drag down):
Increasing safe area inset's content height (drag up):
I have a NavigationSplitView with all three columns, and NavigationLinks in the sidebar to present different Lists for the content column. When a list item is selected in the content view, I want to present a view in the detail view. Since different detail views should be presented for different content views, I represent state like this (some details omitted for space):
// Which detail view to show in the third column
enum DetailViewKind: Equatable {
case blank
case localEnv(RegistryEntry)
case package(SearchResult)
}
// Which link in the sidebar was tapped
enum SidebarMenuItem: Int, Hashable, CaseIterable {
case home
case localEnvs
case remoteEnvs
case packageSearch
}
// Binds to a DetailViewKind, defines the activate SidebarMenuItem
struct SidebarView: View {
@State private var selectedMenuItem: SidebarMenuItem?
@Binding var selectedDetailView: DetailViewKind
var body: some View {
VStack(alignment: .leading, spacing: 32) {
SidebarHeaderView()
Divider()
// Creates the navigationLinks with a SidebarMenuRowView as labels
SidebarMenuView(selectedMenuItem: $selectedMenuItem, selectedDetailView: $selectedDetailView)
Spacer()
Divider()
SidebarFooterView()
}
.padding()
.frame(alignment: .leading)
}
}
struct SidebarMenuRowView: View {
var menuItem: SidebarMenuItem
@Binding var selectedMenuItem: SidebarMenuItem?
@Binding var selectedDetailView: DetailViewKind
private var isSelected: Bool {
return menuItem == selectedMenuItem
}
var body: some View {
HStack {
Image(systemName: menuItem.systemImageName).imageScale(.small)
Text(menuItem.title)
Spacer()
}
.padding(.leading)
.frame(height: 24)
.foregroundStyle(isSelected ? Color.primaryAccent : Color.primary)
.background(isSelected ? Color.menuSelection : Color.clear)
.clipShape(RoundedRectangle(cornerRadius: 10))
.navigationDestination(for: SidebarMenuItem.self) { item in
navigationDestinationFor(menuItem: item, detailView: $selectedDetailView)
}
.onTapGesture {
if menuItem != selectedMenuItem {
selectedMenuItem = menuItem
}
}
}
}
// Determines which detail view to present
struct DetailView: View {
@Binding var selectedDetailView: DetailViewKind
var innerView: some View {
switch selectedDetailView {
case .blank:
AnyView(Text("Make a selection")
.font(.subheadline)
.foregroundStyle(.secondary)
.navigationSplitViewColumnWidth(min: 200, ideal: 350))
case .localEnv(let regEntry):
AnyView(EnvironmentDetailView(regEntry: regEntry))
case .package(let searchResult):
AnyView(PackageDetailView(searchResult: searchResult))
}
}
var body: some View {
innerView
}
}
struct ContentView: View {
@State private var detailView: DetailViewKind = .blank
var body: some View {
NavigationSplitView {
SidebarView(selectedDetailView: $detailView)
.navigationSplitViewColumnWidth(175)
} content: {
HomeView()
.navigationSplitViewColumnWidth(min: 300, ideal: 450)
}
detail: {
DetailView(selectedDetailView: $detailView)
}
}
}
My issue is that the detail view is not updated when the ContentView's detailView property is updated. I've verified that the value itself is changing, but the view is not. I searched around to see why this would be (this is my first Swift/SwiftUI application) and from what I gather a @Binding alone will not cause a view to be updated, that binding either needs to be used in the view hierarchy, or it needs to be stored as a @State property that gets updated when the binding value changes. I added a dummy @State property to DetailView and that still doesn't work, so I'm a little confused:
struct DetailView: View {
@Binding var selectedDetailView: DetailViewKind
@State private var dummyProp: DetailViewKind?
var innerView: some View {
switch selectedDetailView {
case .blank:
AnyView(Text("Make a selection")
.font(.subheadline)
.foregroundStyle(.secondary)
.navigationSplitViewColumnWidth(min: 200, ideal: 350))
case .localEnv(let regEntry):
AnyView(EnvironmentDetailView(regEntry: regEntry))
case .package(let searchResult):
AnyView(PackageDetailView(searchResult: searchResult))
}
}
var body: some View {
innerView.onChange(of: selectedDetailView) {
dummyProp = selectedDetailView
}
}
}
Any ideas?
Topic:
UI Frameworks
SubTopic:
SwiftUI
how to save the state of my APP when I open another APP so that It can restore when I re-open it?
my app will use over 10mb memory so if I open another APP(my app will go background) it will closed at all.
when I re-open it it will restart.
but I do not want it I want if I open Page A and then it go background and when I re-open it it still is Page A and do not restart.
Hello,
I am currently encountering an issue where SwiftUI View Previews cannot be displayed when the View is defined in a Static Framework target. This issue only occurs under specific conditions.
Environment
Xcode: 16.2
Scheme Structure:
MainApp
Test Target: TestHogeFeature
Test Setting:
Gather coverage (Code coverage collection) enabled(all)
Target Structure:
MainApp (Application target)
Dependencies: [HogeFeature, Core]
HogeFeature (Static Framework target)
Dependencies: [Core]
Core (Framework target)
Dependencies: None
TestHogeFeature (Unit test target)
Dependencies: [HogeFeature]
Summary
I am currently working on a SwiftUI-based project and have encountered an issue where Previews fail to display under specific conditions. Below are the details:
Issue
In the MainApp scheme, when the code coverage collection setting (Gather coverage for) is enabled, Previews for SwiftUI Views within the HogeFeature (Static Framework) target fail to display correctly. However, the issue is resolved by taking one of the following actions:
Change HogeFeature from a Static Framework to a Dynamic Framework.
Remove the build setting MACH_O_TYPE: staticlib
Disable the Gather coverage setting in the MainApp scheme.
I have attached the actual error log from the failed Preview.
preview error log
Questions
Why does this issue occur only when using a Static Framework with code coverage enabled?
Is there any way to resolve this issue while maintaining the current configuration (Static Framework with code coverage enabled)?
I would appreciate any advice or insights regarding the cause and potential solutions.
I’m building a SwiftUI app where the struct AppGroup is identified by a UUID and stored in a dictionary. My Task model has appGroupId: UUID?. In TaskDetailView, I create a custom Binding<AppGroup> from the store, then navigate to AppGroupDetailView. However, when I tap the NavigationLink, the console spams logs, CPU hits 100%, and it never stabilizes.
Relevant Code
AppGroupStore (simplified)
class AppGroupStore: ObservableObject {
@Published var appGroupsDict: [UUID: AppGroup] = [:]
func updateAppGroup(_ id: UUID, appGroup: AppGroup) {
appGroupsDict[id] = appGroup
}
// Returns a binding so views can directly read/write the AppGroup by id
func getBinding(withId id: UUID?) -> Binding<AppGroup> {
Binding(
get: {
if let id = id {
return self.appGroupsDict[id] ?? .empty
}
return .empty
},
set: { newValue in
print("New value set for \(newValue.name)")
self.updateAppGroup(newValue.id, appGroup: newValue)
}
)
}
// ...
}
AppGroup is a simple struct:
struct AppGroup: Identifiable, Codable {
let id: UUID
var name: String
var apps: [String]
static let empty = AppGroup(id: UUID(), name: "Empty", apps: [])
}
TaskDetailView (main part)
struct TaskDetailView: View {
@Binding var task: ToDoTask // has task.appGroupId: UUID?
@EnvironmentObject var appGroupStore: AppGroupStore
var body: some View {
let appGroup = appGroupStore.getBinding(withId: task.appGroupId)
print("Task load") // prints infinitely, CPU 100%
return List {
// ...
NavigationLink(destination: AppGroupDetailView(appGroup: appGroup)) {
Text(appGroup.wrappedValue.name)
}
}
.navigationTitle(task.name)
}
}
AppGroupDetailView (simplified)
struct AppGroupDetailView: View {
@Binding var appGroup: AppGroup
// ...
var body: some View {
List {
ForEach(appGroup.apps, id: \.self) { app in
Text(app)
}
}
.navigationTitle(appGroup.name)
}
}
Symptoms:
Tapping the NavigationLink leads to infinite “Task load” logs and 100% CPU usage.
The set closure (“New value set for...”) is never called, so it’s not repeatedly writing.
If I replace the Binding<AppGroup> with a read-only approach (just accessing the dictionary), it does not get stuck.
Question:
What might cause SwiftUI to keep re-rendering the body indefinitely, even if my custom get closure doesn’t explicitly mutate the state? Are there known pitfalls when using a dictionary-based store and returning a Binding like this?
Any help is much appreciated!
Thanks in advance for your insights!
I'm trying to make the side bar menu on my tvOS app have the same behavior of Apple's tvOS App. I would like to have the side menu collapsed at the cold start of the app. I'm trying to achieve this by using the defaultFocus view modifier, which should make the button inside the TabView focused at the start of the app. But no matter what I do, the side bar always steels the focus from the inside button.
struct ContentView: View {
enum Tabs {
case viewA
case viewB
}
enum ScreenElements {
case button
case tab
}
@FocusState private var focusedElement: ScreenElements?
@State private var selectedTab: Tabs? = nil
var body: some View {
Group {
TabView(selection: $selectedTab) {
Tab("View A", image: "square", value: .viewA) {
Button("View A Button", action: {})
.frame(maxWidth: .infinity, alignment: .center)
.focused($focusedElement, equals: .button)
}
}
.tabViewStyle(.sidebarAdaptable)
.focused($focusedElement, equals: .tab)
}
.defaultFocus($focusedElement, .button, priority: .userInitiated)
}
}
Is there a way to start the side bar menu collapsed at the start up of the app?
Anyone know how to reduce the padding between list section header (plain style) and search bar? I have tried all available method on google but none work. The default list style does not have this big padding/space between the section header and the search bar.
struct Demo: View {
@State private var searchText: String = ""
var body: some View {
NavigationStack {
List {
Section {
ForEach(0..<100) { index in
Text("Sample value for \(index)")
}
} header: {
Text("Header")
.font(.headline)
}
}
.listStyle(.plain)
.navigationTitle("Demo")
.navigationBarTitleDisplayMode(.inline)
.searchable(text: $searchText)
}
}
}
If I show a textfield in my app and set nothing else on it but the following, The keyboard will show an autofill suggestion from a password manager for a one time code.
textField.keyboardType = .numberPad
In this case, the text field is for typing in a count, so iOS suggesting to autofill a one time code is incorrect.
Setting textField.textContentType to nil has no affect on the behaviour.
Prerequisites to reproduce
an app with an associated domain
an entry in a password manager with a one time code for the domain
a textfield with keyboardType set to numberPad
I am having issues with my app on visionOS. It works fine on iOS. The app is presenting a ImagePicker, I had tried converting to PhotoPicker and the behavior did not change.
The relevant code is in the EditGreetingCardView -
//
// Created by Michael Rowe on 1/2/24.
//
import AVKit
import SwiftData
import SwiftUI
struct EditGreetingCardView: View {
@Environment(\.modelContext) private var modelContext
@Environment(\.dismiss) private var dismiss
@Query(sort: \EventType.eventName) private var events: [EventType]
var greetingCard: GreetingCard?
private var editorTitle: String { greetingCard == nil ? "Add Greeting Card" : "Edit Greeting Card" }
@State var frontImageSelected: Image? = Image("frontImage")
@State var sourceType: UIImagePickerController.SourceType = .photoLibrary
@State var frontPhoto = false
@State var captureFrontImage = false
var eventTypePassed: EventType?
@State private var eventType: EventType?
@State private var cardName = ""
@State private var cardManufacturer = ""
@State private var cardURL = ""
@State private var cardUIImage: UIImage?
@State private var cameraNotAuthorized = false
@State private var isCameraPresented = false
@State private var newEvent = false
@AppStorage("walkthrough") var walkthrough = 1
init(eventTypePassed: EventType?) {
if let eventTypePassed {
_eventType = .init(initialValue: eventTypePassed)
}
}
init(greetingCard: GreetingCard?) {
self.greetingCard = greetingCard
_eventType = .init(initialValue: greetingCard?.eventType)
}
var body: some View {
NavigationStack {
Form {
Section("Occasion") {
Picker("Select Occasion", selection: $eventType) {
Text("Unknown Occasion")
.tag(Optional<EventType>.none) //basically added empty tag and it solve the case
if events.isEmpty == false {
Divider()
ForEach(events) { event in
Text(event.eventName)
.tag(Optional(event))
}
}
}
}
.foregroundColor(Color("AccentColor"))
Section("Card details") {
}
.foregroundColor(Color("AccentColor"))
Section("Card Image") {
HStack(alignment: .center){
Spacer()
ZStack {
Image(uiImage: cardUIImage ?? UIImage(named: "frontImage")!)
.resizable()
.aspectRatio(contentMode: .fit)
.shadow(radius: 10 )
Image(systemName: "camera.fill")
.foregroundColor(.white)
.font(.largeTitle)
.shadow(radius: 10)
.frame(width: 200)
.onTapGesture { self.frontPhoto = true }
.actionSheet(isPresented: $frontPhoto) { () -> ActionSheet in
#if !os(visionOS)
ActionSheet(
title: Text("Choose mode"),
message: Text("Select one."),
buttons: [
ActionSheet.Button.default(Text("Camera"), action: {
checkCameraAuthorization()
self.captureFrontImage.toggle()
self.sourceType = .camera
}),
ActionSheet.Button.default(Text("Photo Library"), action: {
self.captureFrontImage.toggle()
self.sourceType = .photoLibrary
}),
ActionSheet.Button.cancel()
]
)
#else
ActionSheet(
title: Text("Choose mode"),
message: Text("Select one."),
buttons: [
ActionSheet.Button.default(Text("Photo Library"), action: {
self.captureFrontImage.toggle()
self.sourceType = .photoLibrary }),
ActionSheet.Button.cancel()
]
)
#endif
}
.fullScreenCover(isPresented: $captureFrontImage) {
#if !os(visionOS)
ImagePicker(
sourceType: sourceType,
image: $frontImageSelected)
.interactiveDismissDisabled(true)
#else
ImagePicker(
image: $frontImageSelected)
.interactiveDismissDisabled(true)
#endif
}
}
.frame(width: 250, height: 250)
Spacer()
}
}
}
.alert(isPresented: $cameraNotAuthorized) {
Alert(
title: Text("Unable to access the Camera"),
message: Text("To enable access, go to Settings > Privacy > Camera and turn on Camera access for this app."),
primaryButton: .default(Text("Settings")) {
openSettings()
}
,
secondaryButton: .cancel()
)
}
.toolbar {
}
.onAppear {
}
.onChange(of: frontImageSelected) { oldValue, newValue in
cardUIImage = newValue?.asUIImage()
}
}
}
}
Topic:
UI Frameworks
SubTopic:
SwiftUI
We were using below delegate methods from QuickLook to get modified PDF file URL after the sketching But we are not able see the multi line text properly laid out on PDF and part of text missing. Same time Other pencil kit tools are working as expected.
`func previewController(_ controller: QLPreviewController, didSaveEditedCopyOf previewItem: QLPreviewItem, at modifiedContentsURL: URL)
func previewController(_ controller: QLPreviewController, didUpdateContentsOf previewItem: any QLPreviewItem)`
We tested all code in iOS 18.2.
Please let us know if the text edited URL on PDF can be retrieved in any possible way without tampering text
Hi,
I have an existing AppKit-based Mac app that I have been working on for a few years. For a new feature, I wanted to have the app opened by a different app, so I setup the URL scheme under CFBundleURLTypes in my Info.plist, and adopted this delegate callback:
- (void)application: (NSApplication *)application openURLs:(nonnull NSArray<NSURL *> *)urls
Now when I invoke the URL from the 2nd app, it opens my app correctly, BUT this delegate method isn't called. What's interesting is that if I make a totally new app with a URL scheme and adopt this delegate method, it gets called without a problem!
SO what about my original project could be responsible for this 'opensURLs' method to not be called? I've been searching for a solution for a couple of days without any luck. The macOS app's target has a Deployment Target of 10.15 and I'm running this on macOS12.0 with Xcode 13.
Demo project link
https://cdn.pokekara.com/int/other/1737343007_fbcdee810da429552b12ffa2644d928c.zip
Hello,
I’m encountering the error "Publishing changes from within view updates is not allowed, this will cause undefined behavior". while developing an app using SwiftUI and ARKit.
I have a ObjectTracking class where I update some @Published variables inside a function called processObjectAttributes after detecting objects. However, when I try to update these state variables in the View (like isPositionChecked, etc.), the error keeps appearing.
Here is a simplified version of my code:
class ObjectTracking: ObservableObject {
@Published var isPositionChecked: Bool = false
@Published var isSizeChecked: Bool = false
@Published var isOrientationChecked: Bool = false
func checkAttributes(objectAnchor: ARObjectAnchor,
_ left: ARObjectAnchor.AttributeLocation,
_ right: ARObjectAnchor.AttributeLocation? = nil,
threshold: Float) -> Bool {
let attributes = objectAnchor.attributes
guard let leftValue = attributes[left]?.floatValue else { return false }
let rightValue = right != nil ? attributes[right!]?.floatValue ?? 0 : 0
return leftValue > threshold && (right == nil || rightValue > threshold)
}
func isComplete(objectAnchor: ARObjectAnchor) -> Bool {
isPositionChecked = checkAttributes(objectAnchor: objectAnchor, .positionLeft, .positionRight, threshold: 0.5)
isSizeChecked = checkAttributes(objectAnchor: objectAnchor, .sizeLeft, .sizeRight, threshold: 0.3)
isOrientationChecked = checkAttributes(objectAnchor: objectAnchor, .orientationLeft, .orientationRight, threshold: 0.3)
return isPositionChecked && isSizeChecked && isOrientationChecked
}
func processObjectAttributes(objectAnchor: ARObjectAnchor) {
currentObjectAnchor = objectAnchor
}
}
In my View, I am using @ObservedObject to observe the state of these variables, but the error persists when I try to update them during view rendering.
Could anyone help me understand why this error occurs and how to avoid it? I understand that state should not be updated during view rendering, but I can’t find a solution that works in this case.
Thank you in advance for your help!
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
do {
let shapeLayer = CAShapeLayer()
shapeLayer.frame = CGRect(x: 50, y: 100, width: 200, height: 108)
let path = UIBezierPath(roundedRect: shapeLayer.bounds, cornerRadius: 36)
shapeLayer.path = path.cgPath
shapeLayer.fillColor = UIColor.orange.cgColor
view.layer.addSublayer(shapeLayer)
}
do {
let layer = CALayer()
layer.backgroundColor = UIColor.blue.cgColor
layer.cornerRadius = 36
layer.frame = CGRect(x: 50, y: 300, width: 200, height: 108)
view.layer.addSublayer(layer)
}
}
}
The corner radius is set to 36 through CAShapeLayer, but the actual effect is larger than 36, close to half of the height.
Setting it through CALayer is fine
Can anyone explain it to me? Thank you