带有包含图像和文本的占位符的 UITextField [英] UITextField with a placeholder containing an image and text

查看:28
本文介绍了带有包含图像和文本的占位符的 UITextField的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么办法可以让放大镜图标粘在 UITextField 中的占位符上,如下所示:

is there any way I could have a magnifier icon stuck to my placeholder in a UITextField like the below:

我试图覆盖 leftViewRectForBounds(bounds: CGRect):

override func leftViewRectForBounds(bounds: CGRect) -> CGRect {
    var superRect = super.leftViewRectForBounds(bounds)
    superRect.origin.x += 80
    return superRect
  }

但是没有用

推荐答案

您可以使用 NSAttributedStringNSTextAttachment 将图像添加到文本中.

You can add images to text using NSAttributedString and NSTextAttachment.

我已经有一段时间没有使用它们了,但我相信你可以做这样的事情......

I haven't used them in a while but I believe you can do something like this...

let magnifyingGlassAttachment = NSTextAttachment(data: nil, ofType: nil)
magnifyingGlassAttachment.image = UIImage(named: "MagnifyingGlass")

let magnifyingGlassString = NSAttributedString(attachment: magnifyingGlassAttachment)

现在您可以使用 magnifyingGlassString 属性字符串并将其作为属性文本的一部分添加到 UITextField.

now you can use the magnifyingGlassString attributed string and add it as part of the attributed text to the UITextField.

我相信您还可以准确指定放大镜在字符串旁边的呈现方式(它如何包裹等...)

I believe you can also specify exactly how the magnifying glass renders alongside the string (how it wraps etc...)

这样的东西...

var attributedText = NSMutableAttributedString(attributedString: magnifyingGlassString)

let searchString = NSAttributedString(string: "Search for stuff")

attributedText.appendAttributedString(searchString)

textField.attributedPlaceholder = attributedText

这篇关于带有包含图像和文本的占位符的 UITextField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆