Skip to content

Instantly share code, notes, and snippets.

@jerrypm
Created November 14, 2018 04:10
Show Gist options
  • Select an option

  • Save jerrypm/1f4187c43193fb9d665088c238e19204 to your computer and use it in GitHub Desktop.

Select an option

Save jerrypm/1f4187c43193fb9d665088c238e19204 to your computer and use it in GitHub Desktop.
import Foundation
import UIKit
class CountTextField: UITextField, UITextFieldDelegate {
lazy var countLabel: UILabel = {
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 20, height: 40))
label.font = UIFont.systemFont(ofSize: 12)
label.textAlignment = .center
label.textColor = #colorLiteral(red: 0.1098039216, green: 0.5176470588, blue: 0.8588235294, alpha: 1)
label.text = "16"
return label
}()
let padding = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 0)
override func awakeFromNib() {
delegate = self
let rightView = UIView(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
rightView.addSubview(countLabel)
self.rightView = rightView
rightViewMode = .always
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let newLength = (textField.text?.utf16.count)! + string.utf16.count - range.length
if newLength <= 16 {
countLabel.text = "\(16 - newLength)"
return true
} else {
return false
}
}
open override func textRect(forBounds bounds: CGRect) -> CGRect {
return UIEdgeInsetsInsetRect(bounds, padding)
}
open override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
return UIEdgeInsetsInsetRect(bounds, padding)
}
open override func editingRect(forBounds bounds: CGRect) -> CGRect {
return UIEdgeInsetsInsetRect(bounds, padding)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment