TextInputFilter allows you to write contained and reusable input filters, that can filter and/or transform input as it's typed. The same filters can be used for UITextField
or UITextView
.
These examples show the usage of a basic input filter with UITextField
, but you can also use the same filter with UITextView
.
An input filter can respond to input in three ways:
.accept
: input is applied as-is.transform
: a transformed version of the input is set.reject
: input is rejected and text is not changed
The input filter will install a delegate that handles the shouldChange...
methods, but any other delegate methods are forwarded to the original delegate
(even if it was set after the input filter).
This example shows a very simple input filter that just converts input to uppercase.
import TextInputFilter
struct UppercaseInputFilter: TextInputFilter {
func result(for change: String, appliedTo original: String, replacingRange range: Range<String.Index>, changed: String) -> TextInputFilterResult {
return .transform(changed.uppercased())
}
}
import TextInputFilter
struct UppercaseInputFilter: TextInputFilter {
func result(for change: String, appliedTo original: String, replacingRange range: Range<String.Index>, changed: String) -> TextInputFilterResult {
return .transform(changed.uppercased())
}
}
...
let textField = UITextField(frame: frame)
textField.setInputFilter(UppercaseInputFilter(), onChange: { print("Changed: \($0)") })
textField.delegate = self // You can still use delegate methods other than textField(_:shouldChangeCharactersIn:replacementString:)
TextInputFilter is compatible with Swift 4.x and later, and requires iOS 9.0+
Just drop the files inside the Sources
directory anywhere in your own project.
Download the repo, drag TextInputFilter.xcodeproj
into your own project and link the appropriate target for your platform.
Inside your Podfile
:
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '9.0'
target 'TargetName' do
use_frameworks!
pod 'TextInputFilter'
end
Inside your Cartfile
:
github "fabiorodella/TextInputFilter"
Inside your Package.swift
:
// swift-tools-version:4.0
import PackageDescription
let package = Package(
name: "TargetName",
dependencies: [
.package(url: "https://github.com/fabiorodella/TextInputFilter.git", from: "1.1.0"),
],
targets: [
.target(
name: "TargetName",
dependencies: ["TextInputFilter"]),
]
)