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
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With