How to move cursor when new NSTextView becomes FirstResponder (MacOS)? - swift

Each time the user presses enter, a new NSTextView is made. This works correctly, and the new NSTextView becomes the first responder, as is my goal. However, the cursor does not move into the new NSTextView despite it being the first responder.
Below is my code:
func makeNSView(context: NSViewRepresentableContext<TextView>) -> TextView.NSViewType {
let textView = NSTextView()
textView.textContainer?.lineFragmentPadding = 10
textView.textContainerInset = .zero
textView.font = NSFont.systemFont(ofSize: 12)
textView.becomeFirstResponder()
//NSApp.activate(ignoringOtherApps: true) ----> doesn't make difference but is supposed to help switch cursor
print("\(textView) is first responder") //proof that the first responder is shifting, but the cursor does not move with it for some reason
return textView
}
I have tried to use this line as suggested by a different answer:
NSApp.activate(ignoringOtherApps: true)
However, it doesn't make any difference. I have also tried inserting text at a selected range, but it doesn't insert text in any of the NSTextViews displayed regardless of whether they are the first responder.
What methods exist to move the cursor to a different NSTextView (preferably to the First Responder)?
Let me know if any more information is needed.

I was able to get the desired behaviour by doing this:
func makeNSView(context: NSViewRepresentableContext<TextView>) -> TextView.NSViewType {
let textView = NSTextView()
textView.textContainer?.lineFragmentPadding = 10
textView.textContainerInset = .zero
textView.font = NSFont.systemFont(ofSize: 12)
DispatchQueue.main.async {textView.window?.makeFirstResponder(textView)
textView.setSelectedRange(NSMakeRange(0, 0)) }
print("\(textView) is first responder") //proof that the first responder is shifting, but the cursor does not for some reason
return textView
}
The answer originally comes from here: How to make first responder in SwiftUI macOS
Thanks for all the help!

As Warren Burton mentions in a comment, you have not added the new view to a window's view hierarchy at the point that you're trying to make it the first responder. That can't work.
Furthermore, calling becomeFirstResponder() does not make the receiver the first responder. (This is different from UIKit.) In fact, you're never supposed to call becomeFirstResponder() on macOS (except to forward to the superclass in an override). The documentation calls this out specifically:
Use the NSWindow makeFirstResponder(_:) method, not this method, to make an object the first responder. Never invoke this method directly.
(Emphasis added.) becomeFirstResponder() is called by Cocoa to inform a view (or other responder) that it has become the first responder. It doesn't cause a change, it notifies about a change.
So, once the view has been added to a window's view hierarchy, invoke textView.window.makeFirstResponder(textView).

Related

Swift macOS SegmentedControl Action not getting called

Description
I am trying to use NSSegmentedControls to transition between Child ViewControllers. The ParentViewController is located in Main.storyboard and the ChildViewControllers are located in Assistant.storyboard. Each ChildViewController has a SegmentedControl divided into 2 Segments and their primary use is to navigate between the ChildViewControllers. So they are set up as momentaryPushIn rather than selectOne. Each ChildViewController uses a Delegate to communicate with the ParentViewController.
So in the ParentViewController I added the ChildViewControllers as following:
/// The View of the ParentViewController configured as NSVisualEffectView
#IBOutlet var visualEffectView: NSVisualEffectView!
var assistantChilds: [NSViewController] {
get { return [NSViewController]() }
set(newValue) {
for child in newValue { self.addChild(child) }
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
addAssistantViewControllersToChildrenArray()
}
override func viewWillAppear() {
visualEffectView.addSubview(self.children[0].view)
self.children[0].view.frame = self.view.bounds
}
private func addAssistantViewControllersToChildrenArray() -> Void {
let storyboard = NSStoryboard.init(name: "Assistant", bundle: nil)
let exampleChild = storyboard.instantiateController(withIdentifier: "ExampleChild") as! ExampleChildViewController
let exampleSibling = storyboard.instantiateController(withIdentifier: "ExampleSibling") as! ExampleSiblingViewController
exampleChild.navigationDelegate = self
exampleSibling.navigationDelegate = self
assistantChilds = [exampleChild, exampleSibling]
}
So far so good. The ExampleChildViewController has an NSTextField instance. While I am in the scope of the TextField, I can trigger the action of the SegmentedControls. Its navigating forward and backward as it should. But once I leave the scope of the TextField I can still click the Segments, but they are not triggering any action. They should be able to navigate forward and backward even if the TextField is not the current "First Responder" of the application. I think I am missing something out here, I hope anyone can help me with this. I know the problem is not the NSSegmentedControl because I am seeing the same behavior with an NSButton, which is configured as Switch/Checkbox, in the SiblingViewController. I just don't have any idea anymore what I am doing wrong.
It`s my first time asking a question myself here, so I hope the way I am doing is fine for making progress with the solution. Let me know if I can do something better/different or if I need to provide more information about something.
Thanks in advance!
Additional Information
For the sake of completeness:
The ParentViewController itself is embedded in a ContainerView,
which is owned by the RootViewController. I can't imagine this does
matter in any way, but this way we are not missing something out.
I am actually not showing the navigation action, because I want to
keep it as simple as possible. Furthermore the action is not problem,
it does what I want it to do. Correct me if I am wrong with this.
Possible solutions I found while researching, which did not work for me:
Setting window.delegate of the ChildViewControllers to NSApp.windows.first?.delegate
Setting the ChildViewController to becomeFirstResponder in its func viewWillAppear()
visualEffectView.addSubview(self.children[0].view, positioned: NSWindow.OrderingMode.above, relativeTo: nil)
Related problems/topics I found while researching:
Basic segmented control not working
Adding and Removing Child View Controllers
NSSegmentedControl - Odd appearance when placed in blur view
How to set first responder to NSTextView in Swift?
How to use #selector in Swift 2.2 for the first responder
Accessing methods, actions and/or outlets from other controllers with swift
How to use Child View Controllers in Swift 4.0 programmatically
Container View Controllers
issues with container view
Control a NSTabViewController from parent View
How to detect when NSTextField has the focus or is it`s content selected cocoa
SOLUTION
let parentViewControllerInstance = self.parent as! ParentViewController
segmentedControl.target = parentViewControllerInstance
In my case I just had to set the delegate as the target of the sendAction method.
Background
Ok, after hours of reading the AppKit Documentation I am now able to answer my own question.
First, debugging the UI showed that the problem was definitely not in the ViewHierarchy.
So I tried to think about the nature of NSButton and NSSegmentedControl. At some point I noticed that both are subclasses of NSControl.
class NSSegmentedControl : NSControl
class NSButton : NSControl
The AppKit Documentation says:
Discussion
Buttons are a standard control used to initiate actions within your app. You can configure buttons with many different visual styles, but the behavior is the same. When clicked, a button calls the action method of its associated target object. (...) You use the action method to perform your app-specific tasks.
The bold text points to the key of the solution – of its associated target object. Typically I define the action of an control item like this:
button.action = #selector(someFunc(_:))
This causes the NSControl instance to call this:
func sendAction(_ action: Selector?, to target: Any?) -> Bool
Parameter Description from the documentation:
Parameters
theAction
The selector to invoke on the target. If the selector is NULL, no message is sent.
theTarget
The target object to receive the message. If the object is nil, the application searches the responder chain for an object capable of handling the message. For more information on dispatching actions, see the class description for NSActionCell.
In conclusion the NSControl instance, which was firing the action method (in my case the NSSegmentedControl), had no target to send its action to. So it was only able to send its action method across the responder chain - which obviously has been nil while the first responder was located in another view.

Is it possible use different instance of UIMenuController for UITextField in Swift?

According to link we should use a singleton UIMenuController instance which is referred to the editing menu.
The problem is I want to show extra items in different situations. For instance, I want to just show "copy" item when keyboard is up. and show "copy" and "reply" when tapping on a tableview row.
When I add "reply" to the UIMenuController instance it is shown when tapping on UITextField too. therefore, I added these codes:
func textViewDidBeginEditing(_ textView: UITextView) {
var nonReplyMenuItems: [UIMenuItem] = []
if let allMenuItems = UIMenuController.shared.menuItems {
for menuItem in allMenuItems {
if menuItem.title != "reply".localized {
nonReplyMenuItems.append(menuItem)
}
}
}
UIMenuController.shared.menuItems = nonReplyMenuItems
UIMenuController.shared.setMenuVisible(true, animated: true)
}
It fixed the problem in most situations, but not all.
when keyboard is up and tapping on a row in tableview "reply" will be added. Then when I tap on UITextView the reply will be shown there too.
It seems your scenario is like it:
tap on textfield ----> shows copy
tap on tableview ---> shows copy and reply
tab on textfield ----> shows copy and reply (you want only copy shows)
As I know the textViewDidBeginEditing calls when your text filed is not editing and you tap on that; So if you have two textfileds by switching on that method calls every time but when you are switching between a text filed and another action base object your text field is editing and its state has not changed.
When you touch on tableview you must call textfield.resignFirstResponder() so when you tap on text field again the textViewDidBeginEditing calls again, the problem of this is hiding keyboard; The better way I preferو is adding function to touch down of text field or on gesture to do what you write on textViewDidBeginEditing method

make NSTableView row stay selected Swift

how would I go about making a previously selectedRow of an NSTableView stay selected after the user presses a button calling a method to work with that selectedRow?
It worked in a previous programm looking like this:
selecting it gives it the OSX selection color, clicking the save button makes the textField becomeFirstResponder() which makes the row go grey automatically and doesnt change the selectedRow property. This is not done by my code, so im happy it just works.
Now in a similar program I want to achieve exactly this, but after clicking a button (calling a method making the textField becomeFirstResponder()) the visual selection is gone and also the tableView property selectedRow goes back to -1 (no row selected).
I tried a lot of ideas, most answers online are objective-C. Here is my most recent code (beeing called by the same button and pretty much faking what worked automatically before):
the NSTableViewAction method and the selectedRowCache variable:
var selectedRowCache = -1
#IBAction func alarmDataTableView(_ sender: NSTableView) {
selectedRowCache = alarmDataTableView.selectedRow
}
the buttonAction:
#IBAction func editAlarmButton(_ sender: NSButton) {
let row = alarmDataTableView.rowView(atRow: self.selectedRowCache, makeIfNecessary: false)
row?.backgroundColor = .blue
}
the selectedRowCache is just a variable that saves the selectedRow whenever the user selects a row (i dont want this).
no with this code the background color of the row doesnt do a thing (besides losing its selection after the button method is called).
the NSTableView is view based.
Thank you for any help!

tableViewSelectionDidChange with addSubview and removeFromSuperview in table row

I looked for posts for issues with all 3 functions listed in the title, but my problem is not discussed anywhere. Frankly, my problem is such that it defies logic IMHO.
On selection of a row in my view-based NSTableView, I want to show a "Save" button in my last (aka "Action") column. So on viewDidLoad() I created my orphan button. Then on tableViewSelectionDidChange() I remove it from the superview and add it to my column's NSTableCellView. When there's no row selected, there is no button to show. Simple. Below code works perfectly.
func tableViewSelectionDidChange(_ notification: Notification) {
let selectedRow = tableView.selectedRow
btnSave!.removeFromSuperview()
if selectedRow > -1,
let rowView = rowView(selectedRow),
let actionView = rowView.view(atColumn: Column.action.hashValue) as? NSTableCellView {
actionView.addSubview(btnSave!)
}
}
Wait. Did I say Perfect? It works as long as I use mouse to change the selected row, including selecting below the last row in table which removes selection and any button in previous selected row. However, when I use the keyboard Up/Down keys to change the selection, it does not work.
First I thought the function will get called only if I use mouse to change row selection. However, that's not true. That's true for tableViewSelectionIsChanging as per docs and as per facts. But for tableViewSelectionDidChange docs don't say it will only work when mouse is used and the facts bear that out. I put print statements and function does get called. I stepped through debugger as well. The mind boggling part is - the method to remove button from superview works, but the one to add button as subview does not work - and only if I use keyboard. How is it possible that the same exact code executes but I get two different outcomes?
Adding remaining functions
I use this to get selected row
private func rowView(_ rowIndex: Int, _ make: Bool = false) -> NSTableRowView? {
return tableView.rowView(atRow: rowIndex, makeIfNecessary: make)
}
I call this in viewDidLoad to create my orphan button
private func createButton() {
btnSave = NSButton(frame: NSRect(x: 10, y: 0, width: 22, height: 16))
btnSave?.title = "S"
btnSave?.setButtonType(.momentaryPushIn)
btnSave?.bezelStyle = .roundRect
}

Move a label left from its position in swift

I have put a label in a text box and I want to shift this label to left side after tapping this text box. In the following screenshot 'hello' is a label and I want to shift it left after tapping on the text box.
I wrote the following code but the 'textFieldDidBeginEditing' function is not called
#IBOutlet weak var lblhello: UILabel!
func textFieldDidBeginEditing(numtxt: UITextField!) { //delegate method
lblhello.frame = CGRectMake(98, 156, 42, 21)
}
I'm making the assumption based on previous comments that you want to manually specify the frame size, and aren't using constraints.
First off, you need to add UITextFieldDelegate to your viewController.
This is done like so in the beginning of your VC class:
class yourViewControllerName: UIViewController, UITextFieldDelegate {
Then you want to specify the delegate of your UITextField, (most likely in viewDidLoad)
yourTextFieldName.delegate = self
Now you can use the textFieldDelegate functions. The on you're looking for is probably this:
func textFieldDidBeginEditing(textField: UITextField) -> Bool {
lblhello.frame = CGRectMake(160, 200, 60, 40)
return true
}
If everything is set up correctly that should change the frame of lblhello when a user begins editing your UITextField.
One common problem I often hear for people saying this doesn't work. Is caused by the label being specified in viewDidLoad(). Most of the time you want to declare the label before viewDidLoad(), otherwise functions like this doesn't have access to it.
In case you want to move it back to it's original position afterwards. You do almost the same as you did in textFieldDidBeginEditing except you use textFieldDidEndEditing instead.
However, on a side-note. I do suggest getting used to using constraints rather than setting the frame for things like this.