Select all text in a NSTextField using Swift
Try this in a playground:
import XCPlayground
import AppKit
let view = NSView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
XCPShowView("view", view)
let txtf = NSTextField(frame: CGRect(x: 50, y: 50, width: 200, height: 50))
view.addSubview(txtf)
txtf.stringValue = "falling asleep at the keyboard..."
txtf.selectText(nil) // Ends editing and selects the entire contents of the text field
var txt = txtf.currentEditor() // returns an NSText
txt.selectedRange // --> (0,33)
Command-click on selectedRange
, then on NSText
(its return type), which will jump you to its Swiftened header where you can check out its rich functionality...
Select all text in a UITextField using Swift
textField.becomeFirstResponder()
textField.selectAll(nil)
How can I get Select All working in my subclassed NSTextField/NSTextFieldCell?
The application menu handles sending the keyboard shortcut actions to the application's current first responder. The missing connection would explain why your regular NSTextField
objects are missing this functionality as well.
Select all text in TextField upon click SwiftUI
SwiftUI Solution:
struct ContentView: View {
var body: some View {
TextField("Placeholder", text: .constant("This is text data"))
.onReceive(NotificationCenter.default.publisher(for: UITextField.textDidBeginEditingNotification)) { obj in
if let textField = obj.object as? UITextField {
textField.selectedTextRange = textField.textRange(from: textField.beginningOfDocument, to: textField.endOfDocument)
}
}
}
}
Note : import Combine
Use UIViewRepresentable
and wrap UITextField
and use textField.selectedTextRange
property with delegate.
Here is the sample demo
struct HighlightTextField: UIViewRepresentable {
@Binding var text: String
func makeUIView(context: Context) -> UITextField {
let textField = UITextField()
textField.delegate = context.coordinator
return textField
}
func updateUIView(_ textField: UITextField, context: Context) {
textField.text = text
}
func makeCoordinator() -> Coordinator {
Coordinator(parent: self)
}
class Coordinator: NSObject, UITextFieldDelegate {
var parent: HighlightTextField
init(parent: HighlightTextField) {
self.parent = parent
}
func textFieldDidBeginEditing(_ textField: UITextField) {
textField.selectedTextRange = textField.textRange(from: textField.beginningOfDocument, to: textField.endOfDocument)
}
}
}
For macOS
struct HighlightTextField: NSViewRepresentable {
@Binding var text: String
func makeNSView(context: Context) -> CustomTextField {
CustomTextField()
}
func updateNSView(_ textField: CustomTextField, context: Context) {
textField.stringValue = text
}
}
class CustomTextField: NSTextField {
override func mouseDown(with event: NSEvent) {
if let textEditor = currentEditor() {
textEditor.selectAll(self)
}
}
}
How to get the selected string from a NSTextView in Swift?
What about
let str = mainTextField.text.substring(with: range)
Edit:
This should work now:
let range = mainTextField.selectedRange() // Returns NSRange :-/ (instead of Range)
let str = mainTextField.string as NSString? // So we cast String? to NSString?
let substr = str?.substring(with: range) // To be able to use the range in substring(with:)
Highlight a selection in NSTextField
You may have noticed that an NSTextField
only shows a selection range when it has focus, i.e., is the first responder. In this case, editing is handled by an NSTextView
called the field editor. So, make sure the field has focus (e.g., by using the makeFirstResponder:
method of NSWindow
), then use the NSControl
method currentEditor
to get the field editor, and then you can use the NSText
method setSelectedRange:
.
ObjC
NSText* fieldEditor = [myField currentEditor];
[fieldEditor setSelectedRange: mySelRange];
Swift
let fieldEditor = textfield.currentEditor()
fieldEditor?.selectedRange = range
Deselecting Text in NSTextField
In a simple app with just a window and textfield.
I set the textField to firstResponder.
This makes the text selected when the app runs.
If I add to the the applicationDidFinishLaunching
NSRange tRange = [[ _theTextField currentEditor] selectedRange];
[[ _theTextField currentEditor] setSelectedRange:NSMakeRange(tRange.length,0)];
Now when run the Text is not selected and the insertion point is at the end of the text.
I used selectedRange to get the selection char length. As the text was selected in the first place and seem more simple.
- (void)awakeFromNib{
[_theTextField setStringValue:@"100000"];
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
[[[NSApplication sharedApplication] mainWindow] makeFirstResponder:_theTextField];
NSRange tRange = [[ _theTextField currentEditor] selectedRange];
[[ _theTextField currentEditor] setSelectedRange:NSMakeRange(tRange.length,0)];
}
Related Topics
What Might Be Causing This Animation Bug with Swiftui and Navigationview
How to Apply a Context Menu to Buttons in a Swiftui List Row
Apple Vision - Barcode Detection Doesn't Work for Barcodes with Different Colours
Nested Tabview - Remove Inner Tab Bar iOS 13, Swift Ui
@Objc Redundancy When Having @Objcmembers Private Dynamic Var
Nswindow with Round Corners in Swift
Swift Conditional Conformances with Generic Type
Uisearchbar's Set_Cancelbuttontext: Ivar Is Prohibited
Closures Return Value (Previously Completionblock)
Ibdesignable and Uitableviewcell
Xcode UI Test:Accessibility Query Fail on Uitableviewcell
How to Get the Unicode Codepoint Represented by an Integer in Swift
Nsurlsessiondatadelegate Method Didreceivedata and Others Are Not Called
Appending Text to Nstextview in Swift 3
How to Process an Array of Task Asynchronously with Swift Combine