swift开源库iOSer 的自我修养iOS程序猿

分别用OC和Swift做图文混排-基础demo

2016-10-07  本文已影响268人  vvkeep

使用OC和Swift完成图片和文字在一起如下图的效果:

demo效果图

OC版本

- (void)viewDidLoad {
    [super viewDidLoad];
    //属性文本 Attachment - 附件
    
    NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
    attachment.image = [UIImage imageNamed:@"d_aini"];
    //lineHeight 大致和字体大小相等
    CGFloat height = self.label.font.lineHeight;
    attachment.bounds = CGRectMake(0, -3, height, height);
    
    NSAttributedString *imageStr = [NSAttributedString attributedStringWithAttachment:attachment];
    
    //定义一个可变的属性字符串
    NSMutableAttributedString *attrMStr= [[NSMutableAttributedString alloc] initWithString:@"我"];
    //拼接图片文本
    [attrMStr appendAttributedString:imageStr];
    [attrMStr appendAttributedString:[[NSAttributedString alloc] initWithString:@"爱你"]];
    
    
    //设置属性文本
    self.label.attributedText = attrMStr;
}

Swift版本

    @IBOutlet weak var label: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        //创建一个属性文本
        //图片附件
        let attactment = NSTextAttachment()
        attactment.image = #imageLiteral(resourceName: "d_aini")
        
        let imageStr  = NSAttributedString(attachment: attactment)
        let height = label.font.lineHeight
        attactment.bounds = CGRect(x: 0, y: -3, width: height, height: height)
        
        
        let attrStr = NSAttributedString(string: "我")
        let mAttrStr = NSMutableAttributedString(attributedString: attrStr)
        mAttrStr.append(imageStr)
        mAttrStr.append(NSAttributedString(string: "爱你"))
        
        label.attributedText = mAttrStr
    }
上一篇下一篇

猜你喜欢

热点阅读