NSAttributedString:图像未显示在UILabel中

时间:2015-08-02 05:14:03

标签: swift uiimage uilabel nsattributedstring

由于某种原因,图像不显示。我已经在Image.xcassets /下面删除了test.png和test@2x.png,我也把它放在了项目中。这些都没有帮助。非常感谢任何帮助。

    var testView: UILabel = UILabel(frame: CGRectMake(20, 20, self.view.frame.width-40, self.view.frame.height-40))
 var a = "Testing..."

    var attachment = NSTextAttachment()
    //This is the image that I would like to add 
    // I have dropped test.png and test@2x.png under Image.xcassets

    attachment.image = UIImage(named: "test")

    var attachmentString = NSAttributedString(attachment: attachment)
    let attrsB = NSAttributedString(
        string: "2nd line..Testing testing",
        attributes: NSDictionary(
            object: UIFont(name: "HelveticaNeue", size: 18.0)!,
            forKey: NSFontAttributeName) as [NSObject : AnyObject])



    a.appendAttributedString(attrsB)
    let attributedTextToDisplay = NSMutableAttributedString(attributedString: a)

    attributedTextToDisplay.appendAttributedString(attachmentString)

    testView.attributedText = attributedTextToDisplay

    self.view.addSubview(testView)

1 个答案:

答案 0 :(得分:0)

如果要显示多行,则需要允许标签有多行。

var testView: UILabel = UILabel(frame: CGRectMake(20, 20, self.view.frame.width-40, self.view.frame.height-40))
testView.numberOfLines = 0;

提示:

  1. 使用故事板& Interface Builder。 WYSIWYG。
  2. 使用AutoLayout,它解决了很多大小调整问题
  3. 如果您不确定变量的内容
  4. ,请使用断言
  5. 进入调试器并按下眼睛图标以显示 quicklook
  6. 消除所有这些变量将帮助您找出根本原因,而不必担心,无论您的图像是否被加载。见下面的示例。
  7. 为了获得好的衡量标准,我还明确地将a输入a:NSMutableAttributedString

    var a:NSMutableAttributedString
    

    enter image description here