【问题标题】:UIImage next to centered UITextField Placeholder Text居中的 UITextField 占位符文本旁边的 UIImage
【发布时间】:2017-08-04 05:57:00
【问题描述】:

在 UITextField 的居中占位符文本旁边对齐 UIImage 图标的最佳方法是什么?前任:

一段时间以来,我一直在尝试复制它,但似乎无法达到预期的效果。

我尝试使用 UITextField 的 LeftView,但是无法使其与占位符文本对齐(我曾考虑通过更改其框架向 LeftView 添加填充,但我不确定如何获得对齐所需的值它在占位符旁边。似乎无法获取占位符文本的坐标。)。我也尝试将 UITextField 子类化,但这里再次不确定如何获得正确的坐标。

【问题讨论】:

    标签: ios swift uitextfield


    【解决方案1】:

    您可以使用NSTextAttachment在属性字符串中附加图像

    Swift 3.0

    txtField.textAlignment = .center
    let attachment = NSTextAttachment()
    attachment.image = UIImage(named: "searchIcon")
    attachment.bounds = CGRect(x: 0, y: 0, width: 10, height: 10)
    let attachmentStr = NSAttributedString(attachment: attachment)
    let myString = NSMutableAttributedString(string: "")
    myString.append(attachmentStr)
    let myString1 = NSMutableAttributedString(string: "Find a Location (Zip Code or Name)")
    myString.append(myString1)
    txtField.attributedPlaceholder = myString
    

    Objective-C

    NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
    attachment.image = [UIImage imageNamed:@"searchIcon"];
    attachment.bounds = CGRectMake(0, 0, 10, 10);
    NSAttributedString *attachmentStr = [NSAttributedString attributedStringWithAttachment:attachment];
    NSMutableAttributedString *myString = [[NSMutableAttributedString alloc] initWithString:@""];
    [myString appendAttributedString:attachmentStr];
    NSMutableAttributedString *myString1 = [[NSMutableAttributedString alloc] initWithString:@"Find a Location (Zip Code or Name)"];
    [myString appendAttributedString:myString1];
    txtField.attributedPlaceholder = myString;
    

    【讨论】:

      猜你喜欢
      • 2012-07-17
      • 2011-04-09
      • 2016-05-10
      • 2013-09-13
      • 2016-10-07
      • 2015-12-26
      • 1970-01-01
      • 1970-01-01
      • 2016-02-02
      相关资源
      最近更新 更多