Last active
June 18, 2020 05:06
-
-
Save Yorzic/8182ba88efe4a2e4caf60c4d2171a434 to your computer and use it in GitHub Desktop.
UITableViewCell with limit on the number of characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode 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