Custom InputView Keyboard Height [duplicate] - swift

This question already has answers here:
iOS Custom keyboard increase UIInputViewController height
(1 answer)
Unable to change UIInputView height
(4 answers)
Closed 8 months ago.
I have made a custom keyboard using a .xib and .swift file. I set it for a textfield by doing the following:
let customNumberPad = CustomNumberPad()
length.inputView = customNumberPad.inputView
However, the size of the keyboard area is large like it is using the old keyboard.
I have tried setting the height in the .xib to 200 via constraint.
I have tried:
length.inputView!.autoresizingMask = []
let heightAnch = length.inputView!.heightAnchor.constraint(equalToConstant: 200)
heightAnch.isActive = true
length.reloadInputViews()
Full CustomNumberPad code:
import UIKit
import AudioToolbox
class CustomNumberPadSmall: UIInputViewController {
#IBOutlet var numberPad: UIView!
#IBAction func insertText(_ sender: UIButton) {
if let text = sender.currentTitle {
AudioServicesPlaySystemSound (1104)
self.textDocumentProxy.insertText(text)
}
}
#IBAction func backSpace(_ sender: UIButton) {
self.textDocumentProxy.deleteBackward()
}
override func viewDidLoad() {
super.viewDidLoad()
overrideUserInterfaceStyle = USERINFO.darkModeValue
Bundle.main.loadNibNamed("CustomNumberPadSmall", owner: self)
numberPad.translatesAutoresizingMaskIntoConstraints = false
let inputView = self.inputView!
inputView.translatesAutoresizingMaskIntoConstraints = false
inputView.addSubview(numberPad)
NSLayoutConstraint.activate([
numberPad.topAnchor.constraint(equalTo: inputView.topAnchor),
numberPad.bottomAnchor.constraint(equalTo: inputView.bottomAnchor),
numberPad.leadingAnchor.constraint(equalTo: inputView.leadingAnchor),
numberPad.trailingAnchor.constraint(equalTo: inputView.trailingAnchor),
numberPad.heightAnchor.constraint(equalToConstant: 200)
])
}
}

If you only need a number pad it's better to use keyboardType property of UITextField.
yourTextField.keyboardType = .numberPad
In another case you need a custom keyboard itself, override intrinsicContentSize property of UIInputView
class CustomNumberPad: UIInputView {
// your calculated input view height
var intrinsicHeight: CGFloat = 200 {
didSet {
self.invalidateIntrinsicContentSize()
}
}
init() {
super.init(frame: CGRect(), inputViewStyle: .keyboard)
self.translatesAutoresizingMaskIntoConstraints = false
}
required init?(coder: NSCoder) {
super.init(coder: coder)
self.translatesAutoresizingMaskIntoConstraints = false
}
override var intrinsicContentSize: CGSize {
return CGSize(width: UIView.noIntrinsicMetric, height: self.intrinsicHeight)
}
}
How to use :
let customNumberPad = CustomNumberPad()
yourTextField.inputView = customNumberPad

Related

SwiftUI Representable TextField changes Font on disappear

I am using a Representable ViewController for a custom NSTextField in SwiftUI for MacOS. I am applying a customized, increased font size for that TextField. That works fine, I had a question regarding that topic in my last question here.
I am setting the Font of the TextField in my viewDidAppear() method now, which works fine. I can see a bigger font. The problem is now, when my view is not being in focus, the text size is shrinking back to normal. When I go back and activate the window again, I see the small font size. When I type again, it gets refreshed and I see the correct font size.
That is my code I am using:
class AddTextFieldController: NSViewController {
#Binding var text: String
let textField = NSTextField()
var isFirstResponder : Bool = true
init(text: Binding<String>, isFirstResponder : Bool = true) {
self._text = text
textField.font = NSFont.userFont(ofSize: 16.5)
super.init(nibName: nil, bundle: nil)
NSLog("init")
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
textField.delegate = self
//textField.font = NSFont.userFont(ofSize: 16.5)
self.view = textField
}
override func viewDidAppear() {
self.view.window?.makeFirstResponder(self.view)
textField.font = NSFont.userFont(ofSize: 16.5)
}
}
extension AddTextFieldController: NSTextFieldDelegate {
func controlTextDidChange(_ obj: Notification) {
if let textField = obj.object as? NSTextField {
self.text = textField.stringValue
}
textField.font = NSFont.userFont(ofSize: 16.5)
}
}
And this is the representable:
struct AddTextFieldRepresentable: NSViewControllerRepresentable {
#Binding var text: String
func makeNSViewController(
context: NSViewControllerRepresentableContext<AddTextFieldRepresentable>
) -> AddTextFieldController {
return AddTextFieldController(text: $text)
}
func updateNSViewController(
_ nsViewController: AddTextFieldController,
context: NSViewControllerRepresentableContext<AddTextFieldRepresentable>
) {
}
}
Here is a demo:
I thought about using Notification when the view is coming back, however not sure
NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: NSApplication.willBecomeActiveNotification, object: nil)
Here is a solution. Tested with Xcode 11.4 / macOS 10.15.4
class AddTextFieldController: NSViewController {
#Binding var text: String
let textField = MyTextField() // << overridden field
and required custom classes (both!!) for cell & control (in all other places just remove user font usage as not needed any more):
class MyTextFieldCell: NSTextFieldCell {
override var font: NSFont? {
get {
return super.font
}
set {
// system tries to reset font to default several
// times (here!), so don't allow that
super.font = NSFont.userFont(ofSize: 16.5)
}
}
}
class MyTextField: NSTextField {
override class var cellClass: AnyClass? {
get { MyTextFieldCell.self }
set {}
}
override var font: NSFont? {
get {
return super.font
}
set {
// system tries to reset font to default several
// times (and here!!), so don't allow that
super.font = NSFont.userFont(ofSize: 16.5)
}
}
}

Centering a view with auto constraints - Swift

I am creating an XIB/class of datePicker which is called programatically from a calling viewController when the user taps a button. How can I use auto constraints to place this view immediately below and aligned with the centre of the calling button. My code works in portrait, but fails when the device is rotated (the datePicker does not re-center). Probably because I am passing a CGRect as an argument on init of the view, which doesn't change on rotate. I can't see any other way of overriding the passing of CGRect. When I add in auto constraints code, I get run-time auto formatting errors.
ViewController:
#IBAction func showMyDatePicker(_ sender: Any) {
showMyDatePicker.isEnabled = false
let today = Date()
let minDate = Calendar.current.date(byAdding: .month, value: -3, to: today)
let maxDate = Calendar.current.date(byAdding: .month, value: 3, to: today)
let datePickerWidth = 300
let datePickerHeight = 200
let datePickerX = Int(showMyDatePicker.center.x - CGFloat(datePickerWidth / 2))
let datePickerY = Int(showMyDatePicker.center.y + CGFloat(showMyDatePicker.bounds.height / 2))
let frame = CGRect(x: datePickerX, y: datePickerY, width: datePickerWidth, height: datePickerHeight)
myDatePicker = MyDatePicker(frame: frame)
myDatePicker?.setMyDatePicker(date: today, minimumDate: minDate!, maximumDate: maxDate!)
myDatePicker?.delegate = self
self.view.addSubview(myDatePicker!)
}
datePickerClass:
class MyDatePicker: UIView {
var delegate: MyDatePickerDelegate?
#IBOutlet var contentView: UIView!
#IBOutlet weak var datePicker: UIDatePicker!
#IBOutlet weak var returnButton: UIButton!
#IBAction func datePickerChanged(_ sender: Any) {
delegate?.dateFromDatePicker(date: datePicker.date, closeDatePickerView: false)
}
#IBAction func returnButtonTapped(_ sender: Any) {
delegate?.dateFromDatePicker(date: datePicker.date, closeDatePickerView: true)
}
override init(frame: CGRect) {
super.init(frame: frame)
initView()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
initView()
}
private func initView() {//QUESTION: how can I set the datepicker initial values within here
// Instantiate the view from xib file
let contentView = Bundle.main.loadNibNamed("MyDatePicker", owner: self, options: nil)?.first as? UIView
// Check that it's not nil
guard contentView != nil else {
return
}
// Add the view and set its frame
addSubview(contentView!)
contentView?.frame = self.bounds
contentView?.autoresizingMask = [.flexibleHeight, .flexibleWidth]
}
func setMyDatePicker(date: Date, minimumDate: Date, maximumDate: Date) {
datePicker.date = date
datePicker.minimumDate = minimumDate
datePicker.maximumDate = maximumDate
}
}
Just add the required constraint after addSubview and setting TAMIC to false as follows:
#IBAction func showMyDatePicker(_ sender: UIButton) {
// ...
view.addSubview(myDatePicker!)
myDatePicker.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
myDatePicker.topAnchor.constraint(equalTo: sender.bottomAnchor),
myDatePicker.centerXAnchor.constraint(equalTo: sender.centerXAnchor)])
}

Change search field's icon

I try to implement search behavior like in Xcode: if you enter something in search field, icon changes color.
I delegate both searchFieldDidStartSearching and searchFieldDidEndSearching to controller and change the image.
The problem is icon's image changes only when window lose it's focus.
class ViewController: NSViewController {
#IBOutlet weak var searchField: NSSearchField!
func searchFieldDidStartSearching(_ sender: NSSearchField) {
print("\(#function)")
(searchField.cell as! NSSearchFieldCell).searchButtonCell?.image = NSImage.init(named: "NSActionTemplate")
}
func searchFieldDidEndSearching(_ sender: NSSearchField) {
print("\(#function)")
(searchField.cell as! NSSearchFieldCell).searchButtonCell?.image = NSImage.init(named: "NSHomeTemplate")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
Thanks in advance for any ideas/suggestions.
Although I don't know the reason, it works:
NSApp.mainWindow?.resignMain()
NSApp.mainWindow?.becomeMain()
Here is the whole code:
class MyViewController: NSViewController {
private lazy var searchField: NSSearchField = {
let searchField = NSSearchField(string: "")
if let searchButtonCell = searchField.searchButtonCell {
searchButtonCell.setButtonType(.toggle)
let filterImage = #imageLiteral(resourceName: "filter")
searchButtonCell.image = filterImage.tinted(with: .systemGray)
searchButtonCell.alternateImage = filterImage.tinted(with: .systemBlue)
}
searchField.focusRingType = .none
searchField.bezelStyle = .roundedBezel
searchField.delegate = self
return searchField
}()
...
}
extension MyViewController: NSSearchFieldDelegate {
func searchFieldDidStartSearching(_ sender: NSSearchField) {
sender.searchable = true
}
func searchFieldDidEndSearching(_ sender: NSSearchField) {
sender.searchable = false
}
}
extension NSSearchField {
var searchButtonCell: NSButtonCell? {
(self.cell as? NSSearchFieldCell)?.searchButtonCell
}
var searchable: Bool {
get {
self.searchButtonCell?.state == .on
}
set {
self.searchButtonCell?.state = newValue ? .on : .off
self.refreshSearchIcon()
}
}
private func refreshSearchIcon() {
NSApp.mainWindow?.resignMain()
NSApp.mainWindow?.becomeMain()
}
}
extension NSImage {
func tinted(with color: NSColor) -> NSImage? {
guard let image = self.copy() as? NSImage else { return nil }
image.lockFocus()
color.set()
NSRect(origin: NSZeroPoint, size: self.size).fill(using: .sourceAtop)
image.unlockFocus()
image.isTemplate = false
return image
}
}
I was having the same issue. A simple override fixed this issue for me
extension NSSearchField{
open override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
}
}
As you can see when you click inside the view it's still focussed on the search text field(as you can still type in it after you clicked underneath it). Since the change image is on when it loses focus, you should check if you clicked outside of the text field.
Solve problem by subclassing NSSearchFieldCell and assign this class to field's cell.
You don't even need to subclass NSSearchFieldCell.
When you create your NSSearchField from code, you can do something like this:
if let searchFieldCell = searchField.cell as? NSSearchFieldCell {
let image = NSImage(named: "YourImageName")
searchFieldCell.searchButtonCell?.image = image
searchFieldCell.searchButtonCell?.alternateImage = image // Optionally
}
If you're using storyboards, you can do the same in didSet of your #IBOutlet.

Subclassing NSControl, IBAction is not called in Swift

I've subclassed an NSSlider that behaves differently whether the option key is pressed. In order to do that, I overrode the mouseDown func. It seems to do the job.
The thing is, I've noticed the connected #IBAction in my ViewController is only triggered when the option key is unpressed (i.e. when the mouseDown method is passed to super). What am I missing in order to allow the #IBAction to perform?
Many thanks
Besides the issue, improvement advices on the code are welcome... :-)
Josh
class ViewController: NSViewController {
#IBOutlet weak var theSlider: MySlider!
#IBAction func moveSlider(sender: NSSlider) {
print(sender.floatValue) //works only with optionKey unpressed
}
}
class MySlider: NSSlider { //Implemented in another source file
#IBInspectable var multiplier: Float = 0.5
private var modifierKeys = NSEventModifierFlags.AlternateKeyMask
private var optionKeyPressed = false
private var previousSliderPosition: Float = 0.0
//MARK: Init with NSCoder
required init?(coder: NSCoder) {
super.init(coder: coder)
Swift.print("init Coder called")
self.continuous = true
NSEvent.addLocalMonitorForEventsMatchingMask(.FlagsChangedMask) { (theEvent) -> NSEvent? in
self.flagsChanged(theEvent)
return theEvent
}
}
//MARK: Mouse tracking
override func mouseDown(theEvent: NSEvent) {
if optionKeyPressed {
var keepOn = true
previousSliderPosition = self.floatValue * Float(self.bounds.width) / Float(self.maxValue)
while keepOn {
if let nextEvent = self.window?.nextEventMatchingMask(Int(NSEventMask.LeftMouseUpMask.rawValue) | Int(NSEventMask.LeftMouseDraggedMask.rawValue))
{
switch nextEvent.type
{
case .LeftMouseDragged:
let mouseInnerLocationX = Float(self.convertPoint(nextEvent.locationInWindow, fromView: self.superview).x)
let mouseDelta = mouseInnerLocationX - previousSliderPosition
let newSliderPosition = previousSliderPosition + (mouseDelta) * multiplier
self.floatValue = newSliderPosition * Float(self.maxValue) / Float(self.bounds.width)
break
case .LeftMouseUp:
keepOn = false
break
default:
break
}
}
}
} else {
super.mouseDown(theEvent)
}
}
//MARK: Option key handling
override func flagsChanged(theEvent: NSEvent) {
if (theEvent.modifierFlags.rawValue & NSEventModifierFlags.DeviceIndependentModifierFlagsMask.rawValue) == NSEventModifierFlags.AlternateKeyMask.rawValue {
optionKeyPressed = true
} else {
optionKeyPressed = false
}
}
}
If you're not calling super.mouseDown, you need to send the action yourself:
sendAction(action, to: target)
sendAction(_:to:), action and target are existing members of NSControl.

Swift function textfield got focus OSX

Currently I am having multiple textfields in a view. If the user taps at one of them there should be a function responding to the event. Is there a way on how to do react (if a textfield got the focus)? I tried it with the NSTextFieldDelegate method but there is no appropriate function for this event.
This is how my code looks at the moment:
class ViewController: NSViewController, NSTextFieldDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let textField = NSTextField(frame: CGRectMake(10, 10, 37, 17))
textField.stringValue = "Label"
textField.bordered = false
textField.backgroundColor = NSColor.controlColor()
view.addSubview(textField)
textField.delegate = self
let textField2 = NSTextField(frame: CGRectMake(30, 30, 37, 17))
textField2.stringValue = "Label"
textField2.bordered = false
textField2.backgroundColor = NSColor.controlColor()
view.addSubview(textField2)
textField2.delegate = self
}
func control(control: NSControl, textShouldBeginEditing fieldEditor: NSText) -> Bool {
print("working") // this only works if the user enters a charakter
return true
}
}
The textShouldBeginEditing function only handles the event if the user tries to enter a character but this isn't what I want. It has to handle the event if he clicks on the textfield.
Any ideas, thanks a lot?
Edit
func myAction(sender: NSView)
{
print("aktuell: \(sender)")
currentObject = sender
}
This is the function I want to call.
1) Create a subclass of NSTextField.
import Cocoa
class MyTextField: NSTextField {
override func mouseDown(theEvent:NSEvent) {
let viewController:ViewController = ViewController()
viewController.textFieldClicked()
}
}
2) With Interface building, select the text field you want to have a focus on. Navigate to Custom Class on the right pane. Then set the class of the text field to the one you have just created.
3) The following is an example for ViewController.
import Cocoa
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
func textFieldClicked() -> Void {
print("You've clicked on me!")
}
}
4) Adding text fields programmatically...
import Cocoa
class ViewController: NSViewController {
let myField:MyTextField = MyTextField()
override func viewDidLoad() {
super.viewDidLoad()
//let myField:MyTextField = MyTextField()
myField.setFrameOrigin(NSMakePoint(20,70))
myField.setFrameSize(NSMakeSize(120,22))
let textField:NSTextField = NSTextField()
textField.setFrameOrigin(NSMakePoint(20,40))
textField.setFrameSize(NSMakeSize(120,22))
self.view.addSubview(myField)
self.view.addSubview(textField)
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
func textFieldClicked() -> Void {
print("You've clicked on me!")
}
}
I know it’s been answered some while ago but I did eventually find this solution for macOS in Swift 3 (it doesn’t work for Swift 4 unfortunately) which notifies when a textfield is clicked inside (and for each key stroke).
Add this delegate to your class:-
NSTextFieldDelegate
In viewDidLoad() add these:-
imputTextField.delegate = self
NotificationCenter.default.addObserver(self, selector: #selector(textDidChange(_:)), name: Notification.Name.NSTextViewDidChangeSelection, object: nil)
Then add this function:-
func textDidChange(_ notification: Notification) {
print("Its come here textDidChange")
guard (notification.object as? NSTextView) != nil else { return }
let numberOfCharatersInTextfield: Int = textFieldCell.accessibilityNumberOfCharacters()
print("numberOfCharatersInTextfield = \(numberOfCharatersInTextfield)")
}
Hope this helps others.