如何将 UIImage 放在 UILabel 前面 - Swift

How to put UIImage in front of UILabel - Swift

我有一个 UILabel,说明用户来自哪里(位置),我想在文本中放一个小图标。

let attachment = NSTextAttachment()
attachment.image = UIImage(named: "geolocationIcon")
let attachmentString:NSAttributedString = NSAttributedString(attachment: attachment)
let myString: NSMutableAttributedString = NSMutableAttributedString(string: location + " ")
myString.appendAttributedString(attachmentString)
otherUserLocationLabel.attributedText = myString

目前显示如下

http://s16.postimg.org/vsnd8v5g1/UILABEL.jpg

如何将图标放在文字前面? 谢谢!

更新

我最终创建了一个自定义 UIButton,然后简单地添加了 UIImage 和 Text,如下所示。

            otherUserLocationButton.setImage(UIImage(named: "geolocationIcon"), forState: .Normal)
            otherUserLocationButton.setTitle(" " + location, forState: .Normal)
    let label = UILabel(frame: CGRectMake(50, 50, 300, 21))
    label.center = CGPointMake(160, 284)
    [![label.textAlignment = NSTextAlignment.Center][1]][1]
    label.text = "Location text"
    label.layer.borderWidth = 0.5
    label.layer.borderColor = UIColor.blueColor().CGColor

    let image: UIImage = UIImage(named: "image_name")!

    var bgImage: UIImageView?
    bgImage = UIImageView(image: image)
    bgImage!.frame = CGRectMake(0,0,20,20)

    label.addSubview(bgImage!)

    self.view.addSubview(label)