Forked from nicklockwood/UITextField+TrailingPlaceholder.swift
Created
January 23, 2022 14:37
-
-
Save mumer92/03a0444afee9d5f247ad0b2914c9eac3 to your computer and use it in GitHub Desktop.
This file contains 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
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) | |
if self.window?.screen.scale == 3 { | |
// Fix for slight baseline misalignment on @3x displays | |
label.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