I have a basic Xcode project where I am adding a swift file with the below AppIntent. This causes the AppIntent action to be added in the Shortcuts app in MacOS. I wanted to know how is this AppIntent directly be able to add the Intent action in the shortcuts app. I have checked the build setting in the Xcode project but I did not find anything being generated that could have caused this. Can someone help me understand what internally happens that causes the action to be added to the shortcuts app?
import AppIntents
import SwiftUI
@available(macOS 13, *)
struct TWIntent: AppIntent {
static let title: LocalizedStringResource = "TWMeditationIntent"
static var description = IntentDescription("try adding this sample action as your TW shortcut")
static var parameterSummary: some ParameterSummary {
Summary("Get information on \(\.$TWType)")
}
// we can have multiple parameter of diff types
@Parameter(title: "TWType", description: "The type to get information on.")
var TWType: String
func perform() async throws -> some IntentResult & ReturnsValue<String> & ProvidesDialog {
NSLog(AppDelegate.TAG + "Inside perform() in MeditationIntent")
return .result(value: TWType, dialog: "Logged a 15 minute break.\(TWType)")
}
}
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
I have created an intent using AppIntent and this intent(TWIntent in the code below) can be seen in the shortcuts app as an action to create the shortcut.
I am using AppShortcutProvider to create the shortcut so that user can directly make use of it. However, my shortcut does not appear in the shortcut app. The phrases used also do not launch the intent in the spotlight search. Below is my AppShortcutProvider file:
@available(macOS 13.0, *)
struct TWShortcuts: AppShortcutsProvider {
static var appShortcuts: [AppShortcut] {
AppShortcut(
intent: TWIntent(),
phrases: [
"Open Intent in \(.applicationName)",
"Open \(.applicationName) Intent",
"Open my Intent in \(.applicationName)",
"Open my \(.applicationName) Intent",
"Open TWIntent"
],
shortTitle: "Open TWIntent",
systemImageName: "rectangle.stack.fill"
)
}
static var shortcutTileColor: ShortcutTileColor = .lightBlue
}
Is there something I m missing? Also can these phrases be used for siri launch in macOS because the documentation mentions that macOS does not have siri capability?
Below is my AppIntent file:
import SwiftUI
@available(macOS 13, *)
struct TWIntent: AppIntent {
static let title: LocalizedStringResource = "TWIntent"
static var description = IntentDescription("try adding this sample action as your TW shortcut")
//launch app on running action
static var openAppWhenRun: Bool = false
static var parameterSummary: some ParameterSummary {
Summary("Get information on \(\.$TWType)")
}
@Parameter(title: "TWType", description: "The type to get information on.")
var TWType: String
func perform() async throws -> some IntentResult & ReturnsValue<String> & ProvidesDialog {
//perform essential task here to update the application content
return .result(value: TWType, dialog: "Logged a 15 minute break.\(TWType)")
}
}
I have a bundled application that contains a widget extension. On launching the application once the widget appears in the widget gallery, However, I have observed that If my widget extension is not sandboxed, the widget fails to show in the widget gallery. Is this expected? I am using the same xcode project and just that AppSandbox capability for the widget extension target is causing this. Can someone please explain why is this happening?
I have created a progress indicator to simulate some progressing download task in the dock icon. However, I can see the progress bar appearing in the dock icon but it is not getting updated when I invoked the updateProgress() method. Ideally it should have updated it, and I m not able to figure out the reason?
I have creating the same NSProgressIndicator on an NSWindow and it works to update the progress bar with the same code. Anything that I m missing to understand here? Below is the code I m using:
class AppDelegate: NSObject, NSApplicationDelegate {
var progressIndicator: NSProgressIndicator!
let dockTile = NSApp.dockTile
func applicationWillFinishLaunching(_ notification: Notification) {
// Step 1: Create a progress bar (NSProgressIndicator)
progressIndicator = NSProgressIndicator(frame: NSRect(x: 10, y: 10, width: 100, height: 20))
progressIndicator.isIndeterminate = false
progressIndicator.minValue = 0.0
progressIndicator.maxValue = 100.0
progressIndicator.doubleValue = 0.0
progressIndicator.style = .bar
dockTile.contentView = progressIndicator
dockTile.display()
//// Update the progress bar for demonstration
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.updateProgress(50)
}
}
func updateProgress(_ value: Double) {
progressIndicator.doubleValue = value
NSApp.dockTile.display()
}
}
I am creating a UIKit application but that contains SwiftUI Views embedded using the hostingcontroller.
I have a particular approach for it..but it requires instantiating a swiftUI view, creating a hostingcontroller object from it and storing a reference to it. So that later If I wanted to update the view, I can simply get the reference back and update the swiftUI view using it.
I wanted to understand what does apple recommends on this. Can we store a swiftUI instance? Does it cause any issue or it is okay to do so?
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 have a UITextField in my application, and I want to detect all the keys uniquely to perform all relevant task. However, there is some problem in cleanly identifying some of the keys.
I m not able to identify the backspace key press in the textField(_:shouldChangeCharactersIn:replacementString:) method.
Also I don't know how to detect the Caps Lock key.
I am intending to so this because I want to perform some custom handling for some keys. Can someone help me with what is the way of detecting it under the recommendation from apple. Thanks in advance.
Note: checking for replacementString parameter in shouldChangeCharactersIn method for empty does not help for backspace detection as it overlaps with other cases.
I'm working on a macOS application that needs to query the list of available printers using NSPrinter.printerNames. For performance reasons, I'd like to perform this operation on a background thread.
However, since NSPrinter is part of AppKit, and AppKit is generally not thread-safe unless explicitly stated, I want to confirm:
Is it safe to call NSPrinter.printerNames from a background thread?
I couldn’t find explicit guidance in the documentation regarding the thread-safety of printerNames, so any clarification or best practices would be appreciated.
Thanks in advance!
Note: I tested this api on a background thread in code and it did not give any error.
In UIKit, UIButton provides a configuration property which allows us to create and customize a UIButton.Configuration instance independently (on a background thread or elsewhere) and later assign it to a UIButton instance. This separation of configuration and assignment is very useful for clean architecture and performance optimization.
Questions:
Is this configuration-style pattern (creating a configuration object separately and assigning it later) available or planned for other UIKit components such as UILabel, UITextField, UISlider, etc.?
Similarly, in AppKit on macOS, are there any components (e.g. NSButton, NSTextField) that support a comparable configuration object mechanism that can be used the same way — constructed separately and assigned to the view later?
This would help in building consistent configuration-driven UI frameworks across Apple platforms. Any insight or official guidance would be appreciated.
I’m working with UIButton and finding different examples for event handling. Currently, I have a single action method like this, which receives the sender and the UIEvent:
@objc func buttonHandler(_ sender: UIButton, forEvent event: UIEvent) {
if let touches = event.allTouches, let touch = touches.first {
switch touch.phase {
case .began: print("TouchDown")
case .ended:
if sender.bounds.contains(touch.location(in: sender)) {
print("TouchUpInside")
} else {
print("TouchUpOutside")
}
case .cancelled: print("TouchCancel")
default: break
}
}
if event.type == .presses {
print("PrimaryActionTriggered")
}
}
Is this considered best/recommended practice in UIKit, or should I use separate selector methods for each event type (e.g. .touchDown, .touchUpInside, .touchUpOutside) using addTarget(_:action:for:)?
Are there any advantages or disadvantages to using a single handler with UIEvent versus multiple selectors for UIControlEvents?
Thanks in advance!
Hi,
I came across the following API:
@MainActor
func placeCursor(at position: UITextPosition!, animated: Bool)
From the signature, it seems intended to move the insertion point (caret) to a given UITextPosition, with an option for animation.
However, UITextView and UITextField don’t seem to expose this method as a public member — calling it gives the error:
Value of type 'UITextView' has no member 'placeCursor'
My questions are:
Is placeCursor(at:animated:) a public, supported API that we can safely use in apps?
If not, what is the Apple-recommended way to programmatically move the cursor without animation?
Right now, I only know of updating selectedTextRange, which works but doesn’t involve this placeCursor method. I want to confirm if placeCursor is meant for developer use or is an internal/private API.
Thanks!
Hello,
I am building a UIKit application where I need to handle key events in a UITextField with the following requirements:
Normal key presses (e.g. A, B, etc.) should insert characters into the text field.
A hotkey combination (Ctrl+K) should trigger a custom computation that runs on a background thread, and once completed, its result (e.g. $) should be inserted into the text field.
All events (normal keys and hotkeys) must appear in the exact order they were pressed by the user. For example:
If the user types A, B, then Ctrl+K, the field should show AB$.
If the user types A, Ctrl+K, C, the field should show A$C, even if the computation for $ takes longer.
I want strict sequential processing: no later keystroke should be inserted until an earlier hotkey computation finishes.
I have tried overriding pressesBegan(_:with:) in a custom UITextField subclass, and I can detect both normal keys and Ctrl+K.
Questions:
Is there a recommended UIKit API or pattern for handling this kind of ordered key event processing with hotkeys?
Are there best practices for mixing UI updates with background computations in this context, while preserving event order?
Thanks!
Hi,
I’m working with custom text input handling in a UITextView. For simulating user typing programmatically, the documented way is to call:
textView.insertText("H")
This correctly inserts text, triggers delegate callbacks, updates the caret, and behaves as expected.
However, since physical keyboard input normally goes through pressesBegan(:with:) before being translated into insertText(:), I was wondering:
Is it possible (or supported) to call pressesBegan ourselves with a constructed UIPress/UIKey to simulate key input events in the same way the system does?
Or
Is the intended approach strictly to use insertText(_:) for simulating text entry, and pressesBegan should only ever be used for listening to actual hardware key presses?
Thanks!
Topic:
UI Frameworks
SubTopic:
UIKit
I’m trying to transform user keyboard input in a TextField so that, for example, whenever the user types the letter "a" it is stored and shown as the Greek letter "α".
I created a custom Binding to intercept and modify the typed text before saving it to my observable model.
Here’s a simplified version of my code:
import SwiftUI
class User: ObservableObject {
@Published var username: String = ""
}
struct ContentView: View {
@ObservedObject var user = User()
var usernameBinding: Binding<String> {
Binding(
get: { user.username },
set: { newValue in
// Replace all "a" with "α"
user.username = newValue.replacingOccurrences(of: "a", with: "α")
}
)
}
var body: some View {
TextField("Username", text: usernameBinding)
.padding()
.onChange(of: user.username) { newValue in
print("username changed to:", newValue)
}
}
}
When I type "a", I can see in the console that the onChange handler prints the transformed string ("α"), and the model (user.username) is updated.
However, the TextField on screen still shows the original "a" instead of updating to "α" immediately.
I expected the text field to update its displayed value whenever the bound property changes (since username is @Published on an ObservableObject), but that doesn’t seem to happen when I modify the text in the binding’s set closure.
Is this a known limitation of SwiftUI TextField?
Is there a better way to transform user input so the field shows the transformed text based on some processing?
Any advice or explanation would be appreciated.
I’m running into an issue with TextField focus behavior in SwiftUI.
By default, when I set focus to a TextField programmatically (using @FocusState), SwiftUI behaves like AppKit — the entire contents of the text field are selected. This is causing problems for my use case, because I want the caret placed at the end of the text without selecting everything.
How I solved this in AppKit
In AppKit, I worked around this by subclassing NSTextField and overriding becomeFirstResponder to adjust the editor’s selection:
override func becomeFirstResponder() -> Bool {
let responderStatus = super.becomeFirstResponder()
// Ensure caret is placed at the end, no text selected
if let editor = self.currentEditor() {
let selectedRange = editor.selectedRange
editor.selectedRange = NSRange(location: selectedRange.length, length: 0)
}
return responderStatus
}
This successfully prevented AppKit from auto-selecting the entire string when focus changed.
The problem in SwiftUI
Now I see the same auto-select behavior in SwiftUI when I toggle focus with @FocusState. But unlike AppKit, SwiftUI doesn’t expose the underlying NSTextView or UITextField APIs, so I can’t directly adjust the selection or caret position.
Questions:
Is there a way in SwiftUI to control the caret/selection behavior when a TextField becomes focused?
Is there a built-in modifier or @FocusState trick I’m missing?
Has anyone found a reliable SwiftUI-idiomatic approach to ensure the caret is placed at the end of the text instead of selecting all text?
update:
adding my swiftUI code below:
struct TextFieldUI: View {
@ObservedObject var pModel:TextFieldModel
@FocusState private var pIsFocusedState: Bool
var body: some View {
VStack(spacing: 20) {
TextField(pModel.placeholder, text: $pModel.text)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
.focused($pIsFocusedState)
.onChange(of: pModel.isFocused) { old, newValue in
pIsFocusedState = newValue
}
.onChange(of: pIsFocusedState) { old, newValue in
pModel.isFocused = newValue
}
.onAppear {
pIsFocusedState = pModel.isFocused
}
Toggle("Secure Mode", isOn: $pModel.isSecure)
.padding()
}
.padding()
}
}