How to achieve that placeholder text disappears character by character in UITextField

后端 未结 6 1850
挽巷
挽巷 2021-02-18 20:28

Can you please help me.

In UITextField when we provide a placeholder text its placeholder string will be gone when we enter any character. How can I achieve

6条回答
  •  抹茶落季
    2021-02-18 21:20

    I guess this is just what you are looking for. Create your UITextField object with the text _2_-__-__A (not placeholder text). Then, use its view controller as delegate, and add that to the view controller:

    -(BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string{
        if (range.length>1) return NO; // Avoids removing multiple characters at once
        if (range.location==1) range.location++;  // '2' index
        if (range.location==3) range.location++;  // '-' index
        if (range.location==6) range.location++;  // '-' index
        if (range.location==9)  return NO; // 'A' index
        if (range.location==10) return NO; // String end
        if ([string isEqualToString:@""]) return NO; //Avoids removing characters
    
        if (range.length==0) {
            range.length++;
            UITextPosition *beginning = textField.beginningOfDocument;
            UITextPosition *start = [textField positionFromPosition:beginning offset:range.location];
            UITextPosition *end = [textField positionFromPosition:start offset:range.length];
            UITextRange *textRange = [textField textRangeFromPosition:start toPosition:end];
            [textField setSelectedTextRange:textRange];
        }
    
        return YES;
    }
    -(void)textFieldDidBeginEditing:(UITextField*)textField{
        UITextPosition *beginning = textField.beginningOfDocument;
        UITextPosition *start = [textField positionFromPosition:beginning offset:0];
        UITextPosition *end = [textField positionFromPosition:start offset:0];
        UITextRange *textRange = [textField textRangeFromPosition:start toPosition:end];
        [textField setSelectedTextRange:textRange];
    }
    -(BOOL)textFieldShouldReturn:(UITextField*)textField{
        [passwordInput resignFirstResponder];
        return YES;
    }
    

    It should work as intended.

提交回复
热议问题