简体   繁体   中英

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

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 by focus, you mean the user clicks on the UITextField, then what you want is to have your view controller act as a UITextFieldDelegate. You want to implement the optional func textFieldDidBeginEditing(_ textField: UITextField) function. In that function you want to hide the image.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM