In creating a sequenced gesture combining a LongPressGesture and a DragGesture, I found that the combined gesture exhibits two problems:
The @GestureState does not properly update as the gesture progresses through its phases. Specifically, the updating(_:body:) closure (documented here) is only ever executed during the drag interaction. Long presses and drag-releases do not call the updating(_:body:) closure.
Upon completing the long press gesture and activating the drag gesture, the drag gesture remains empty until the finger or cursor has moved. The expected behavior is for the drag gesture to begin even when its translation is of size .zero.
This second problem – the nonexistence of a drag gesture once the long press has completed – prevents access to the location of the long-press-then-drag. Access to this location is critical for displaying to the user that the drag interaction has commenced.
The below code is based on Apple's example presented here. I've highlighted the failure points in the code with // *.
My questions are as follows:
What is required to properly update the gesture state?
Is it possible to have a viable drag gesture immediately upon fulfilling the long press gesture, even with a translation of .zero?
Alternatively to the above question, is there a way to gain access to the location of the long press gesture?
import SwiftUI
import Charts
enum DragState {
case inactive
case pressing
case dragging(translation: CGSize)
var isDragging: Bool {
switch self {
case .inactive, .pressing:
return false
case .dragging:
return true
}
}
}
struct ChartGestureOverlay<Value: Comparable & Hashable>: View {
@Binding var highlightedValue: Value?
let chartProxy: ChartProxy
let valueFromChartProxy: (CGFloat, ChartProxy) -> Value?
let onDragChange: (DragState) -> Void
@GestureState private var dragState = DragState.inactive
var body: some View {
Rectangle()
.fill(Color.clear)
.contentShape(Rectangle())
.onTapGesture { location in
if let newValue = valueFromChartProxy(location.x, chartProxy) {
highlightedValue = newValue
}
}
.gesture(longPressAndDrag)
}
private var longPressAndDrag: some Gesture {
let longPress = LongPressGesture(minimumDuration: 0.2)
let drag = DragGesture(minimumDistance: .zero)
.onChanged { value in
if let newValue = valueFromChartProxy(value.location.x, chartProxy) {
highlightedValue = newValue
}
}
return longPress.sequenced(before: drag)
.updating($dragState) { value, gestureState, _ in
switch value {
case .first(true):
// * This is never called
gestureState = .pressing
case .second(true, let drag):
// * Drag is often nil
// * When drag is nil, we lack access to the location
gestureState = .dragging(translation: drag?.translation ?? .zero)
default:
// * This is never called
gestureState = .inactive
}
onDragChange(gestureState)
}
}
}
struct DataPoint: Identifiable {
let id = UUID()
let category: String
let value: Double
}
struct ContentView: View {
let dataPoints = [
DataPoint(category: "A", value: 5),
DataPoint(category: "B", value: 3),
DataPoint(category: "C", value: 8),
DataPoint(category: "D", value: 2),
DataPoint(category: "E", value: 7)
]
@State private var highlightedCategory: String? = nil
@State private var dragState = DragState.inactive
var body: some View {
VStack {
Text("Bar Chart with Gesture Interaction")
.font(.headline)
.padding()
Chart {
ForEach(dataPoints) { dataPoint in
BarMark(
x: .value("Category", dataPoint.category),
y: .value("Value", dataPoint.value)
)
.foregroundStyle(highlightedCategory == dataPoint.category ? Color.red : Color.gray)
.annotation(position: .top) {
if highlightedCategory == dataPoint.category {
Text("\(dataPoint.value, specifier: "%.1f")")
.font(.caption)
.foregroundColor(.primary)
}
}
}
}
.frame(height: 300)
.chartOverlay { chartProxy in
ChartGestureOverlay<String>(
highlightedValue: $highlightedCategory,
chartProxy: chartProxy,
valueFromChartProxy: { xPosition, chartProxy in
if let category: String = chartProxy.value(atX: xPosition) {
return category
}
return nil
},
onDragChange: { newDragState in
dragState = newDragState
}
)
}
.onChange(of: highlightedCategory, { oldCategory, newCategory in
})
}
.padding()
}
}
#Preview {
ContentView()
}
Thank you!
Post
Replies
Boosts
Views
Activity
I recently updated our CloudKit collaboration invite codebase to use the new UIActivityController and NSItemProvider invitation as described in Apple's documentation. We previously used UICloudSharingController's init(preparationHandler:), which is since deprecated.
We have all of the previous functionality in place: we successfully create a CKShare, send the invite out, engage the share, and collaborate. However, we cannot get the Messages CKShare preview to use our custom image and title (henceforth referred to as “collaboration metadata”). Previously, while using UICloudSharingController's init(preparationHandler:) to commence the share invite, the collaboration metadata successfully displayed in the Messages conversation. Now, we have a generic icon of our app and “Shared with App-Name" title, leading to a loss of contextual integrity for the invite flow.
My question: How do we make the collaboration metadata appear in the Messages conversation?
Here is our code for creating the UIActivityController, NSItemProvider, CKShare, and other related entities. It encapsulates the entire CloudKit CKShare invite setup. You will note that we do configure the CKShare with metadata, and we do set the LPLinkMetadata on the UIActivityItemsConfiguration. GitHub Gist.
The metadata does successfully appear in the UIActivityController and the CKShare's image and title are available to the person receiving the share once they engage it and open it in our app – but the Messages preview item retains the generic message content. Also please note that this issue does occur in the production environment.
As a final note, examining UICloudSharingController's definition leads me to believe that supplying a UIActivityItemSource is the key to getting correct Messages collaboration metadata in place. My efforts at using an item adhering to UIActivityItemSource in the UIActivityViewController used to send the share did not yield the rich previews and displayed metadata I am aiming for.
In our Mac Catalyst app running on macOS, the Edit > Spelling and Grammar > Check Spelling While Typing, Check Grammar With Spelling, and Correct Spelling Automatically preferences are reset with each opening of a new text view. How can we make those preferences persistent? Ie, when someone changes those settings for our app's text view, other incarnations of our app's text views should respect the latest preferences.
We looked at swizzling NSTextView's toggleAutomaticSpellingCorrection:, saving those to NSUserDefaults, and then reading those preferences when we set up our UITextView subclass, and then setting the UITextInputTraits properties accordingly.
However, our approach felt heavy handed, and I'm wondering if we are missing some out-of-the-box functionality that will make those preferences intuitively persistent.
Does anyone have any suggestions? Thank you.
Starting with the macOS version 14.x.x and TextKit1, selecting multiple lines of text triggers a text replacement bug: some of the text on one of the selected lines inadvertently replaces a portion of the selected text.
For example, the bug is exhibited when selecting the following lines:
Carnaroli, Maratelli, or Vialone Nano are best
Vialone Nano cooks quickly – watch it! It also absorbs condiments nicely.
Avoid Baldo, Originario, Ribe and Roma
To trigger the bug, select the three line paragraph using either the cursor or shift with arrow keys. Notice that a portion of the selected text was replaced. Command-Z to undo will allow you to repeat the undesired behavior.
In this case, "e Nano cooks quickly - " is replaced by "Baldo, Originario, Ribe."
This does not occur with all strings or selected strings, but in cases where it does occur, it is perfectly reproducible. It does not occur on iOS. Pasteboard contents are irrelevant. After triggering the bug repeatedly, at some point it stops occurring.
Why does this bug occur? How can it be fixed?
Here is some sample code to reproduce the issue.
@end
@implementation TestNoteViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self createTextView];
}
- (void)createTextView {
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:self.note.text
attributes:nil];
NSTextStorage *textStorage = [NSTextStorage new];
[textStorage appendAttributedString:attrString];
CGRect newTextViewRect = self.view.bounds;
// Create the layout manager
NSLayoutManager *layoutManager = [NSLayoutManager new];
[textStorage addLayoutManager:layoutManager];
// Create a text container
NSTextContainer *container = [[NSTextContainer alloc] initWithSize:CGSizeMake(newTextViewRect.size.width, CGFLOAT_MAX)];
[layoutManager addTextContainer:container];
// Create and place a text view
UITextView *textView = [[UITextView alloc] initWithFrame:newTextViewRect
textContainer:container];
[self.view addSubview:textView];
textView.translatesAutoresizingMaskIntoConstraints = NO;
UILayoutGuide *safeArea = textView.superview.safeAreaLayoutGuide;
[textView.leadingAnchor constraintEqualToAnchor:safeArea.leadingAnchor].active = YES;
[textView.trailingAnchor constraintEqualToAnchor:safeArea.trailingAnchor].active = YES;
[textView.topAnchor constraintEqualToAnchor:safeArea.topAnchor].active = YES;
[textView.bottomAnchor constraintEqualToAnchor:textView.superview.bottomAnchor].active = YES;
}
@end
What is the highest level of location precision achievable with the WeatherKit API? When latitude and longitude are given up to the fifth decimal place, the precision is around 1 meter. Could this ever be more accurate than providing the lat/long to the fourth decimal place, which has a precision of about 10 meters?
Is it possible to use the CKNotificationInfo's desiredKeys property for the CKDatabaseSubscription?
I'd like to use have access to those values in the AppDelegate function...
application:didReceiveRemoteNotification:fetchCompletionHandler:
When I try to create subscriptions with desiredKeys, I get an error reading "cannot add additionalFields to this subscription type."
Is that for real? Can we not use desiredKeys with CKDatabaseSubscriptions?
In attempting to deploy changes made in the development environment to the production environment, the confirmation dialogue shows that all Subscription Types are set to be deleted.
Why?
The Subscription Types are present in the development environment, and there appears to be no way to prevent deletion of the Subscription Types when deploying to production. As you might imagine, I'm worried deploying our changes will break cloud sync for everyone using our apps by invalidating subscriptions.
What's going on here? How can I ensure that CloudKit subscriptions continue to work?
The desirable example is exhibited by the Apple Notes widgets. When adding an Apple Notes widget, WidgetKit goes ahead and assigns an IntentConfiguration to the new widget. You can see this by editing the widget and noticing that the selection element does not read "Choose" but instead includes the name of the note or folder that was automatically selected as default for the new widget. You'll also notice that this placeholder widget's data source does not change from one source to another – the assigned IntentConfiguration is respected.
How can we do this in our Widgets? It should look like this: someone creates a new widget, we use their most recent data item for the placeholder, and that item is 1) persisted in the Widget until they change it 2) reflected in the edit widget dialogue.
Sync between iOS and Mac Catalyst is intermitent. The fundamental issue is slow and inconsistent remote notifications being sent to and received by the Mac Catalyst app.When making changes in the Mac Catalyst app, those changes are successfully pushed to the iCloud private database and the iOS or iPadOS app successfully receives the remote notification indicating the change. In short, the MacOS -> iOS direction is seemless. When making changes in the other direction, we run into problems. A change in the iOS app successfully gets pushed up to the iCloud private database, and other iOS or iPadOS devices successfully receive the remote notification. However, Mac Catalyst apps most commonly will not receive the remote notification at all, or – occassionally – will receive it several minutes after the change took place. Rarely will the Mac Catalyst app receive the notification in a timeframe consistent with the performance of iOS apps (within 2-4 seconds).Why are Mac Catalyst apps having so much trouble receiving these CloudKit-triggered remote notifications? (Note that these issues are present in both development and production environments.)