Skip to content

Instantly share code, notes, and snippets.

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 wb-towa/b8e5004f6b6280de1477f90939b48b51 to your computer and use it in GitHub Desktop.
Save wb-towa/b8e5004f6b6280de1477f90939b48b51 to your computer and use it in GitHub Desktop.
import UIKit
extension UITextField {
/// Add a trailing placeholder label that tracks the text as it changes
func addTrailingPlaceholder(_ placeholder: String) {
let label = UILabel()
label.text = placeholder
label.alpha = 0.3
label.isHidden = true
addSubview(label)
addAction(UIAction { [weak self] _ in
guard let self = self else {
return
}
label.font = self.font
label.frame = self.textRect(forBounds: self.bounds)
label.frame.origin.x = (self.text ?? "").size(withAttributes: [
.font: self.font as Any
]).width
label.isHidden = !self.hasText
}, for: .editingChanged)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment