Skip to content

Instantly share code, notes, and snippets.

@nicklockwood
Last active November 13, 2023 00:25
Show Gist options
  • Star 24 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save nicklockwood/4687ef34c96e332dadab8313e5279ee2 to your computer and use it in GitHub Desktop.
Save nicklockwood/4687ef34c96e332dadab8313e5279ee2 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
let container = UIView()
container.clipsToBounds = true
container.addSubview(label)
addSubview(container)
addAction(UIAction { [weak self] _ in
guard let self = self else {
return
}
label.font = self.font
container.frame = self.textRect(forBounds: self.bounds)
label.frame = container.bounds
if self.window?.screen.scale == 3 {
// Fix for slight baseline misalignment on @3x displays
container.frame.origin.y -= 0.333
}
let size = (self.text ?? "").size(withAttributes: self.defaultTextAttributes)
label.frame.origin.x = size.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