簡體   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