Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am new to Swift so bear with me I want to add an image and text as horizontal align centered in the UITextField. Using following code I was able to add image in the textbox but it is in center and also it remains there when textbox gets focus. I want it in center with placeholder text and when UITextField gets focus it hides.

var imageView = UIImageView()
var image = UIImage(named: "all.png")
imageView.image = image
searchFiled.leftView = imageView
like image 928
Muhammad Saifullah Avatar asked Oct 31 '22 13:10

Muhammad Saifullah


1 Answers

Unfortunately I do not 'speak' Swift, but it should be easily possible to translate the Objective-C version...

Your talking about the so-called 'placeholder'; the string (or attributed string), that is shown in the UITextField, when no really text is inserted.

To show an 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;
like image 155
LaborEtArs Avatar answered Nov 15 '22 07:11

LaborEtArs