vds_ios_sample/VDSSample/Classes/TextField.swift
Matt Bruce 27b0740b0c updated version
fixed issue with keyboard in label not having a minus sign
added helpers in Label for looking at scaled mode
added min lineheight

Signed-off-by: Matt Bruce <matt.bruce@verizon.com>
2023-07-22 09:11:48 -05:00

106 lines
3.0 KiB
Swift

//
// TextField.swift
// VDSSample
//
// Created by Matt Bruce on 8/24/22.
//
import Foundation
import UIKit
import VDS
import VDSFormControlsTokens
import Combine
public class TextField: UITextField {
public var resigner: AnyCancellable?
public var resignAction: ((TextField) -> Void)?
public var isNumeric: Bool = false
public var textPadding = UIEdgeInsets(
top: 10,
left: 10,
bottom: 10,
right: 10
)
public override init(frame: CGRect) {
super.init(frame: frame)
font = TextStyle.bodyLarge.font
setup()
}
public required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func setup() {
keyboardType = .alphabet
returnKeyType = .done
resigner = publisher(for: .editingDidEndOnExit)
.sink { [weak self] _ in
self?.shouldResign()
}
}
public override func textRect(forBounds bounds: CGRect) -> CGRect {
layer.borderColor = UIColor.black.cgColor
layer.borderWidth = VDSFormControls.widthBorder
let rect = super.textRect(forBounds: bounds)
return rect.inset(by: textPadding)
}
public override func editingRect(forBounds bounds: CGRect) -> CGRect {
layer.borderColor = UIColor.black.cgColor
layer.borderWidth = VDSFormControls.widthBorder
let rect = super.editingRect(forBounds: bounds)
return rect.inset(by: textPadding)
}
@objc public func shouldResign() {
if let resignAction {
resignAction(self)
}
resignFirstResponder()
}
}
public class NumericField: TextField {
public override init(frame: CGRect) {
super.init(frame: frame)
isNumeric = true
}
public required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func setup() {
super.setup()
let keypadToolbar: UIToolbar = UIToolbar().with { $0.tintColor = .white; $0.backgroundColor = .white }
// add a done button to the numberpad
keypadToolbar.items=[
UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: self, action: nil),
UIBarButtonItem(title: " - (minus sign)", style: .done, target: self, action: #selector(insertMinus)).with { $0.tintColor = .black},
UIBarButtonItem(title: "Done", style: UIBarButtonItem.Style.done, target: self, action: #selector(shouldResign)).with { $0.tintColor = .black}
]
keypadToolbar.sizeToFit()
// add a toolbar with a done button above the number pad
inputAccessoryView = keypadToolbar
keyboardType = .decimalPad
}
@objc public func insertMinus() {
insertText("-")
}
public var number: NSNumber? {
guard let text, let foundNumber = NumberFormatter().number(from: text) else { return nil }
return foundNumber
}
}