Skip to content

Instantly share code, notes, and snippets.

@Yorzic
Last active June 18, 2020 05:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Yorzic/8182ba88efe4a2e4caf60c4d2171a434 to your computer and use it in GitHub Desktop.
Save Yorzic/8182ba88efe4a2e4caf60c4d2171a434 to your computer and use it in GitHub Desktop.
UITableViewCell with limit on the number of characters
//
// TextFieldWithLabelCell.swift
// Apy
//
// Created by Artur Daylidonis on 20/5/20.
// Copyright © 2020 Artur Daylidonis. All rights reserved.
//
import UIKit
class TextFieldWithLabelCell: UITableViewCell, UITextFieldDelegate {
var maxLength = 100
// Declare callback function variable
var returnValue: ((_ value: String)->())?
@IBOutlet weak var customLabel: UILabel!
@IBOutlet weak var textField: UITextField!
override func awakeFromNib() {
super.awakeFromNib()
textField.delegate = self
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
func textFieldDidChangeSelection(_ textField: UITextField) {
returnValue?(textField.text ?? "")
}
func textFieldDidEndEditing(_ textField: UITextField) {
returnValue?(textField.text ?? "")
}
func textFieldShouldClear(_ textField: UITextField) -> Bool {
true
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// get the current text, or use an empty string if that failed
let currentText = textField.text ?? ""
// attempt to read the range they are trying to change, or exit if we can't
guard let stringRange = Range(range, in: currentText) else { return false }
// add their new text to the existing text
let updatedText = currentText.replacingCharacters(in: stringRange, with: string)
// make sure the result is under 16 characters
return updatedText.count <= maxLength
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment