Post

Replies

Boosts

Views

Activity

detecting modifier keys using UITextFieldDelegate protocol
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.
Topic: UI Frameworks SubTopic: UIKit Tags:
0
0
143
Mar ’25
Is it safe to access NSPrinter.printerNames on a background thread?
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.
Topic: UI Frameworks SubTopic: AppKit Tags:
0
0
117
May ’25
Is configuration-style API (like UIButton.configuration) available for other UIKit or AppKit components?
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.
0
0
83
Jun ’25
Recommended Approach for Handling Multiple UIButton Events: Single Handler vs Multiple Selectors?
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!
Topic: UI Frameworks SubTopic: UIKit Tags:
0
0
63
Aug ’25
Is placeCursor(at:animated:) a public API for moving the text cursor?
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!
Topic: UI Frameworks SubTopic: UIKit Tags:
0
0
91
Sep ’25
How to handle sequential key events with hotkey computation in UITextField (UIKit)
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!
Topic: UI Frameworks SubTopic: UIKit Tags:
0
0
106
Sep ’25
Can pressesBegan be used to simulate text input in a UITextView?
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
0
0
84
Sep ’25
SwiftUI TextField does not update its displayed text when I transform input inside a custom Binding
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.
0
0
75
Sep ’25
SwiftUI TextField selects all text when it gains focus — how to move caret to the end like in AppKit?
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() } }
0
0
101
Sep ’25
How to intercept or prevent user input in SwiftUI TextField when embedding in UIKit
Hi all, I’m working on a UIKit app where I embed a SwiftUI TextField using UIHostingController. I’m using an ObservableObject model to drive the textfield content: class TextFieldModel: ObservableObject { @Published var text: String @Published var placeholder: String @Published var isSecure: Bool @Published var isFocused: Bool init(pText: String, pPlaceholder: String, pIsSecure: Bool, pIsFocused: Bool) { self.text = pText self.placeholder = pPlaceholder self.isSecure = pIsSecure self.isFocused = pIsFocused } } And my SwiftUI view: struct TextFieldUI: View { @ObservedObject var pModel: TextFieldModel @FocusState private var pIsFocusedState: Bool var body: some View { TextField(pModel.placeholder, text: $pModel.text) .focused($pIsFocusedState) } } I embed it in UIKit like this: let swiftUIContentView = TextFieldUI(pModel: model) let hostingController = UIHostingController(rootView: swiftUIContentView) addChild(hostingController) view.addSubview(hostingController.view) hostingController.didMove(toParent: self) Question: In UIKit, if I subclass UITextField, I can override insertText(_:) and choose not to call super, effectively preventing the textfield from updating when the user types. Is there a SwiftUI equivalent to intercept and optionally prevent user input in a TextField, especially when it’s embedded inside UIKit? What is the recommended approach in SwiftUI for this?
0
0
99
Sep ’25
How to detect modifier keys with hardware keyboard in SwiftUI (iOS)?
Hi everyone, In UIKit, I can detect which key and modifier keys are pressed from an external hardware keyboard using the pressesBegan method in a UIResponder: override func pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?) { for press in presses { if let key = press.key { print("Key: \(key.charactersIgnoringModifiers ?? "")") print("Modifiers: \(key.modifierFlags)") } } } I am now working in SwiftUI (iOS), and I couldn’t find a direct equivalent for pressesBegan. What is the recommended way in SwiftUI to detect modifier keys + key presses from an external keyboard? Is there a built-in API, or should I always wrap a UIKit view/controller for this purpose? Thanks in advance!
0
0
54
Sep ’25