繁体   English   中英

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

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

我是Swift的新手,所以请耐心等待我想在UITextField中心添加一个图像和文本作为水平对齐。 使用下面的代码,我能够在文本框中添加图像,但它位于中心,当文本框获得焦点时,它仍然存在。 我希望它在占位符文本的中心,当UITextField获得焦点时,它会隐藏。

var imageView = UIImageView()
var image = UIImage(named: "all.png")
imageView.image = image
searchFiled.leftView = imageView

不幸的是我不会'说'Swift,但是很容易翻译Objective-C版本......

你在谈论所谓的“占位符”; 当没有插入真正的文本时,在UITextField中显示的字符串(或属性字符串)。

要在此处显示图像,请使用以下代码:

    // 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;

如果通过焦点,您的意思是用户单击UITextField,那么您想要的是让您的视图控制器充当UITextFieldDelegate。 您想要实现可选的func textFieldDidBeginEditing(_ textField:UITextField)函数。 在该功能中,您想要隐藏图像。

暂无
暂无

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

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