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

时间:2015-12-19 09:33:48

标签: ios uitextfield swift2

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

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

2 个答案:

答案 0 :(得分:2)

不幸的是我不会'说'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;

答案 1 :(得分:0)

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