简体   繁体   English

如何在UITextField中添加图像和文本作为swift中心的占位符

[英]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 . 我是Swift的新手,所以请耐心等待我想在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. 我希望它在占位符文本的中心,当UITextField获得焦点时,它会隐藏。

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... 不幸的是我不会'说'Swift,但是很容易翻译Objective-C版本......

Your talking about the so-called 'placeholder'; 你在谈论所谓的“占位符”; the string (or attributed string), that is shown in the UITextField , when no really text is inserted. 当没有插入真正的文本时,在UITextField中显示的字符串(或属性字符串)。

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. 如果通过焦点,您的意思是用户单击UITextField,那么您想要的是让您的视图控制器充当UITextFieldDelegate。 You want to implement the optional func textFieldDidBeginEditing(_ textField: UITextField) function. 您想要实现可选的func textFieldDidBeginEditing(_ textField:UITextField)函数。 In that function you want to hide the image. 在该功能中,您想要隐藏图像。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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