94 lines
2.3 KiB
Swift
94 lines
2.3 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
|
|
autocorrectionType = .no
|
|
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()
|
|
keyboardType = .numbersAndPunctuation
|
|
}
|
|
|
|
@objc public func insertMinus() {
|
|
insertText("-")
|
|
}
|
|
|
|
public var number: NSNumber? {
|
|
guard let text, let foundNumber = NumberFormatter().number(from: text) else { return nil }
|
|
return foundNumber
|
|
}
|
|
}
|