Custom FormItem with custom textfield
Vincent-dejong opened this issue · 4 comments
I've set up a custom textfield class, which I would like to implement into a form item, but I can't seem to find where to do this. I've found the CustomFormItem class, however I'm unsure of where to go from here. How do I add the custom textfield to the CustomFormItem?
This is the custom textfield
`
class PostCodeTextField: UITextField, UITextFieldDelegate {
private var characterLimit: Int?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
delegate = self
autocapitalizationType = .allCharacters
}
@IBInspectable var maxLength: Int {
get {
guard let length = characterLimit else {
return Int.max
}
return length
}
set {
characterLimit = newValue
}
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard string.characters.count > 0 else {
return true
}
let currentText = textField.text ?? ""
let prospectiveText = (currentText as NSString).replacingCharacters(in: range, with: string)
return prospectiveText.characters.count <= maxLength
}
`
And I've made a custom class inheriting from CustomFormItem
`
public class PostalCodeFormItem: CustomFormItem {
}
`
Thank in advance!
Try this Vincent
class MyViewController: FormViewController {
override func populate(_ builder: FormBuilder) {
let item = CustomFormItem()
item.createCell = { _ in
return try PostCodeTextField()
}
builder += item
}
}
Ah okay, I see, so instead of inheriting from CustomFormItem I should just be creating a new instance of it. Thanks :)
Only problem I'm still running into is that item.createCell is expecting a UITableViewCell, and my PostCodeTextField is a UITextField. How would I create a tableviewcell that behaves like the other TextFieldFormItems?
For more custom things you will have to make changes to the function PopulateTableView.visit(object: TextFieldFormItem)
and to the class TextFieldFormItemCell
.
Pull requests are welcome 👍
Ah okay, well I took the slightly cheaper but immensely easier approach of using a regular expression specification, which means no fancy automatically changing keyboard, but it gets the job done! 😉
If I ever get around to adding a proper custom form item then I'll be sure to make a pull request!