Swift 用Label显示图片和文字

老规矩,直接上代码。不多说,拿到就能用

       let tuijian = UILabel()
       tuijian.font = UIFont.systemFont(ofSize: 16)
       tuijian.textColor = .black
       tuijian.textAlignment = .center
       self.addSubview(tuijian)
       _=tuijian.sd_layout()
       .topSpaceToView(self,12)?
       .centerXEqualToView(self)?
       .heightIs(22)?.widthIs(100)
        
        // 2.创建图片富文本附件
        
        let voiceAttr = NSMutableAttributedString()
        let imageAttachment = NSTextAttachment()
        let voiceImage = UIImage(named: "新品")
        imageAttachment.image = voiceImage
        imageAttachment.bounds = CGRect(x: 0, y: -2, width: 18, height: 17)
        let imgAttr = NSAttributedString(attachment: imageAttachment)
        voiceAttr.append(imgAttr)
        let textArt = NSAttributedString(string: "新品推荐")
        voiceAttr .append(textArt)
        tuijian.attributedText = voiceAttr
        

 

 效果如图:

Swift 用Label显示图片和文字_第1张图片

 

 

你可能感兴趣的:(Swift,iOS开发)