2016-01-27 2 views
15

Как настроить этот тип анимации в UITextField? В настоящее время многие приложения используют это.Анимация PlaceHolder при вводе текста в TextField в iOS

enter image description here

+0

сделать вам нужно (COOL) анимации для запуска, когда текстовое поле получает фокус, или когда вы хотите переместить фокус с последнего поля? – Russell

+0

Yess Я хочу это .. Или что-то вроде этого .. В настоящее время многие приложения используют это .. –

+1

вы можете использовать другое uilabel или uitextfield для этой задачи, что вам нужно сделать для этого, вы просто добавляете uilabel или utextfiel на него и оставляете его пустым конструктором интерфейса формы, а не устанавливаете текстовое значение для метода, где вы начинаете вводить текст в uitextfield. –

ответ

13

Я нашел решение. Вы можете управлять этим типом анимации с помощью нескольких меток и показывать эти метки в методе textFieldDidBeginEditing.

Если вам нужна хорошая анимация, как вы описали в своем вопросе, попробуйте один раз после третьего репозитория для UITextField.

Если вы ищете UITextView эквивалент этой анимации, пожалуйста, посетите UIFloatLabelTextView хранилище.

+2

UIFloatLableTextField помог мне. Благодаря! –

1

использовать этот код

[your_textfieldname setShowsTouchWhenHighlighted:YES]; 
+0

Что это делает? Я не могу найти его документально, но звучит полезно! – Russell

+0

Я использую этот код в своем приложении, и он отлично работает, как упоминалось в вопросе –

+0

. Я в замешательстве. Я не могу найти его документально, и я просто попробовал его в объективном проекте C, и он не скомпилирован для UITextField ... Было ли это устаревшим? – Russell

2

Вы можете попробовать использовать JSInputField, который поддерживает проверку данных, а также.

JSInputField *inputField = [[JSInputField alloc] initWithFrame:CGRectMake(10, 100, 300, 50)]; 
[self.view addSubview:inputField]; 
[inputField setPlaceholder:@"Enter Text"]; 
[inputField setRoundedCorners:UIRectCornerAllCorners]; 
[inputField addValidationRule:JSCreateRuleNotNullValue]; //This will validate field for null value. It will show error if field is empty. 
[inputField addValidationRule:JSCreateRuleNumeric(2)]; //This will validate field for numeric values and restrict to enter value upto 2 decimal places. 
1

Эта проблема может быть решена логически с использованием нескольких меток и текстовых полей, а затем мы можем при необходимости добавить анимацию. Я хотел бы объяснить эту проблему, используя три изображения: Img1, Img2 и Img3.

Img1 указывает на раскадровку, где мы разработали наш интерфейс. Здесь мы использовали три ярлыка, за которыми следуют TextField и UIView (строка под текстовым полем).

Img2: Он указывает на начальный экран при запуске приложения или когда мы нажимаем кнопку «Зарегистрироваться» внизу, которая сбрасывает экран. В этом изображении метки скрыты, поскольку текстовые поля пусты, а цвет представления - серый.

Img3: Это изображение отражает редактирование текстового поля. По мере того, как мы начинаем редактировать текстовое поле (здесь первое, а именно имя), появляется метка, уменьшается размер текстового поля, изменения замеров и цвет изменения вида на черный.

Нам нужно помнить еще одну вещь, когда мы прекращаем редактирование любого текстового поля, а если оно все еще пустое, то установите его свойства в оригинале.

Я добавляю код для этого Вопроса, который меня задал как задание в интервью.

import UIKit 

class FloatingLabelViewController: UIViewController, UITextFieldDelegate, UINavigationControllerDelegate { 


    //UITextFieldDelegate - protocol defines methods that you use to manage the editing and validation of text in a UITextField object. All of the methods of this protocol are optional. 

    //UINavigationControllerDelegate - Use a navigation controller delegate (a custom object that implements this protocol) to modify behavior when a view controller is pushed or popped from the navigation stack of a UINavigationController object. 

    @IBOutlet weak var NameLbl: UILabel! 
    @IBOutlet weak var EmailLbl: UILabel! 
    @IBOutlet weak var PasswordLbl: UILabel! 

    @IBOutlet weak var NameTxf: UITextField! 
    @IBOutlet weak var EmailTxf: UITextField! 
    @IBOutlet weak var PasswordTxf: UITextField! 

    @IBOutlet weak var SignUpBtn: UIButton! 

    @IBOutlet weak var NameView: UIView! 
    @IBOutlet weak var EmailView: UIView! 
    @IBOutlet weak var PasswordView: UIView! 


    override func viewDidLoad() { 
    super.viewDidLoad() 


    NameTxf.delegate = self 
    EmailTxf.delegate = self 
    PasswordTxf.delegate = self 

    self.property() 

    //black is varaiable here 
    //setTitleColor - Sets the color of the title to use for the specified state 
    //var layer - The view’s Core Animation layer used for rendering. this propert is never nil 
    //cg color - Quartz color refernce 

    SignUpBtn.backgroundColor = UIColor.black 
    SignUpBtn.setTitleColor(UIColor.white, for: .normal) 
    SignUpBtn.layer.borderWidth = 1 
    SignUpBtn.layer.borderColor = UIColor.black.cgColor 

    //Tap guesture recognizer to hide keyboard 
    let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(FloatingLabelViewController.dismissKeyboard)) 
    view.addGestureRecognizer(tap) 

    // UITapGestureRecognizer - UITapGestureRecognizer is a concrete subclass of UIGestureRecognizer that looks for single or multiple taps. For the gesture to be recognized, the specified number of fingers must tap the view a specified number of times. 


    } 

    override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 

    } 

    //textFieldShouldReturn - Asks the delegate if the text field should process the pressing of the return button. The text field calls this method whenever the user taps the return button. YES if the text field should implement its default behavior for the return button; otherwise, NO. 

    // endEditing - Causes the view (or one of its embedded text fields) to resign the first responder status. 

    func textFieldShouldReturn(_ textField: UITextField) -> Bool { 
    self.view.endEditing(true) 
    return false 
    } 


    func dismissKeyboard() { 
    //Causes the view (or one of its embedded text fields) to resign the first responder status. 
    view.endEditing(true) 
    } 

    //When user Starts Editing the textfield 
    // textFieldDidBeginEditing - Tells the delegate that editing began in the specified text field 

    func textFieldDidBeginEditing(_ textField: UITextField) { 

    if textField == self.NameTxf 
    { 

     self.NameTxf.font = UIFont.italicSystemFont(ofSize: 15) 
     self.NameLbl.isHidden = false 
     self.NameLbl.text = self.NameTxf.placeholder 
     self.NameTxf.placeholder = "First Last" 
     NameView.backgroundColor = UIColor.black.withAlphaComponent(0.5) 


    } 

    else if textField == self.EmailTxf 
    { 
     self.EmailTxf.font = UIFont.italicSystemFont(ofSize: 15) 
     self.EmailLbl.isHidden = false 
     self.EmailLbl.text = self.EmailTxf.placeholder 
     self.EmailTxf.placeholder = "[email protected]" 
     EmailView.backgroundColor = UIColor.black.withAlphaComponent(0.5) 


    } 

    else if textField == self.PasswordTxf 
    { 
     self.PasswordTxf.font = UIFont.italicSystemFont(ofSize: 15) 
     self.PasswordLbl.isHidden = false 
     self.PasswordLbl.text = self.PasswordTxf.placeholder 
     self.PasswordTxf.placeholder = "........." 
     PasswordView.backgroundColor = UIColor.black.withAlphaComponent(0.5) 


    } 


    } 


    //When User End editing the textfield. 

    // textFieldDidEndEditing - Tells the delegate that editing stopped for the specified text field. 

    func textFieldDidEndEditing(_ textField: UITextField) { 


    //Checkes if textfield is empty or not after after user ends editing. 
    if textField == self.NameTxf 
    { 
     if self.NameTxf.text == "" 
     { 
     self.NameTxf.font = UIFont.italicSystemFont(ofSize: 25) 
     self.NameLbl.isHidden = true 
     self.NameTxf.placeholder = "Name" 
     NameView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.5) 




    } 


    } 


    else if textField == self.EmailTxf 
    { 
     if self.EmailTxf.text == "" 
     { 
      self.EmailTxf.font = UIFont.italicSystemFont(ofSize: 25) 
      self.EmailLbl.isHidden = true 
      self.EmailTxf.placeholder = "Email" 
      EmailView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.5) 



     } 


    } 



    else if textField == self.PasswordTxf 
    { 
     if self.PasswordTxf.text == "" 
     { 
      self.PasswordTxf.font = UIFont.italicSystemFont(ofSize: 25) 
      self.PasswordLbl.isHidden = true 
      self.PasswordTxf.placeholder = "Password" 
      PasswordView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.5) 


     } 


    } 


    } 

    //Action on SingUp button Clicked. 
    @IBAction func signupClicked(_ sender: Any) { 

     self.property() 
     self.dismissKeyboard() //TO dismiss the Keyboard on the click of SIGNUP button. 

    } 


    //Function to set the property of Textfields, Views corresponding to TextFields and Labels. 
    func property(){ 

    NameLbl.isHidden = true 
    EmailLbl.isHidden = true 
    PasswordLbl.isHidden = true 

    NameTxf.text = "" 
    EmailTxf.text = "" 
    PasswordTxf.text = "" 

    NameTxf.placeholder = "Name" 
    EmailTxf.placeholder = "Email" 
    PasswordTxf.placeholder = "Password" 


    self.NameTxf.font = UIFont.italicSystemFont(ofSize: 25) 
    self.EmailTxf.font = UIFont.italicSystemFont(ofSize: 25) 
    self.PasswordTxf.font = UIFont.italicSystemFont(ofSize: 25) 

    EmailTxf.keyboardType = UIKeyboardType.emailAddress 
    PasswordTxf.isSecureTextEntry = true 
    NameTxf.autocorrectionType = .no 
    EmailTxf.autocorrectionType = .no 

    NameView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.5) 
    EmailView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.5) 
    PasswordView.backgroundColor = UIColor.lightGray.withAlphaComponent(0.5) 
    } 
} 

Img1 : StoryBoard

Img2: Initial ScreenImg3: Textfield Editing

Смежные вопросы