Вот базовое решение, мы не используем ограничения согласно вашему связанному ответу здесь
EDIT
Исправлено, исправлен случай, когда мы очищаем текстовое поле
class ViewController2: UIViewController, UITextFieldDelegate {
@IBOutlet var textField: UITextField!
var label: UILabel!
override func viewWillAppear(_ animated: Bool)
{
setup()
}
func setup()
{
self.view.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(viewTap(sender:))))
textField.placeholder = "My Placeholder"
textField.delegate = self;
label = UILabel.init(frame: textField.frame)
label.font = textField.font;
label.textColor = UIColor.lightGray
label.text = textField.placeholder
label.isHidden = true
self.view.addSubview(label)
}
@objc func viewTap(sender: UITapGestureRecognizer)
{
self.view.endEditing(true)
}
// MARK: - UITextFieldDelegate
func textFieldDidBeginEditing(_ textField: UITextField)
{
label.isHidden = false;
if (textField.text?.isEmpty ?? false) {
textField.placeholder = nil;
UIView.animate(withDuration: 0.2, animations: {
self.label.frame = CGRect.init(
x: self.textField.frame.origin.x - self.label.frame.size.width * 0.1,
y: self.label.frame.origin.y - self.label.frame.size.height,
width: self.label.frame.size.width,
height: self.label.frame.size.height)
let transform = CGAffineTransform(scaleX: 0.8, y: 0.8);
self.label.transform = transform;
})
}
}
func textFieldDidEndEditing(_ textField: UITextField)
{
if (textField.text?.isEmpty ?? false) {
UIView.animate(withDuration: 0.2, animations: {
self.view.layoutIfNeeded()
let transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
self.label.transform = transform;
self.label.frame = self.textField.frame
}) { (Bool) in
textField.placeholder = self.label.text;
self.label.isHidden = true;
}
}
}
}