How to add image and text to UITextField as center placeholder in quick

I am new to Swift, so bear with me. I want to add image and text as horizontal center alignment in a UITextField . Using the following code, I was able to add the image to the text field, but it is in the center, and it also remains there when the text field receives focus. I want it in the center with placeholder text and when the UITextField gets the focus that it hides.

 var imageView = UIImageView() var image = UIImage(named: "all.png") imageView.image = image searchFiled.leftView = imageView 
+5
source share
2 answers

Unfortunately, I do not say "Swift", but you can easily translate the Objective-C version ...

You are talking about the so-called "placeholder"; a string (or attribute string) that appears in a UITextField when no text is inserted.

To display the image here, use the following code:

  // Create a NSTextAttachment with your image NSTextAttachment* placeholderImageTextAttachment = [[NSTextAttachment alloc] init]; placeholderImageTextAttachment.image = [UIImage imageNamed:@"Your image name"]; // Use 'bound' to adjust position and size placeholderImageTextAttachment.bounds = CGRectMake(0, 0, 16, 16); NSMutableAttributedString* placeholderImageString = [[NSAttributedString attributedStringWithAttachment:placeholderImageTextAttachment] mutableCopy]; // Append the placeholder text NSMutableAttributedString* placeholderString = [[NSMutableAttributedString alloc] initWithString:NSLocalizedString(@"Search", nil)]; [placeholderImageString appendAttributedString:placeholderString]; // set as (attributed) placeholder _yourTextField.attributedPlaceholder = placeholderImageString; 
+3
source

If focus, you mean that the user clicks on UITextField, then you want your view controller to work as UITextFieldDelegate. You want to implement the func function textFieldDidBeginEditing (_ textField: UITextField). In this function you want to hide the image.

0
source

Source: https://habr.com/ru/post/1238698/


All Articles