• UILabel


    // 设置label每一行文字的最大宽度
        // 为了保证计算出来的数值 跟 真正显示出来的效果 一致
        self.contentLabel.preferredMaxLayoutWidth = [UIScreen mainScreen].bounds.size.width - 20;

    下面通过例子,给UILabel的文字后面跟上一个表情

    //创建NSTextAttachment
        NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
        attachment.image = [UIImage imageNamed:@"emoji"];
    
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"后面跟着图片"];
        [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 6)];
        [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:NSMakeRange(0, 6)];
        NSAttributedString *attachmentString = [NSAttributedString attributedStringWithAttachment:attachment];
        [attributedString insertAttributedString:attachmentString atIndex:6];
    
        //设置attributedText
        _label.attributedText = attributedString;

    效果如下:
    这里写图片描述

    上图的例子中,emoji图片偏大,位置也偏上,如何调整?参考Center NSTextAttachment image next to single line UILabel

    可以通过调整bounds来解决:

        NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
        attachment.image = [UIImage imageNamed:@"emoji"];
        attachment.bounds = CGRectMake(0, -5, 20, 20);

    调整之后的效果如下:
    这里写图片描述

    也可以继承NSTextAttachment,然后重写- (CGRect)attachmentBoundsForTextContainer:(NSTextContainer *)textContainer proposedLineFragment:(CGRect)lineFrag glyphPosition:(CGPoint)position characterIndex:(NSUInteger)charIndex方法:

    @interface MYNSAttachment : NSTextAttachment
    @end
    
    @implementation MYNSAttachment
    
    - (CGRect)attachmentBoundsForTextContainer:(NSTextContainer *)textContainer proposedLineFragment:(CGRect)lineFrag glyphPosition:(CGPoint)position characterIndex:(NSUInteger)charIndex
    {
        return CGRectMake( 0 , -5 , lineFrag.size.height , lineFrag.size.height);
    }
    @end

    UIFont

    UIFont代表字体,常见创建方法有以下几个:
    + (UIFont *)systemFontOfSize:(CGFloat)fontSize;   系统默认字体
    + (UIFont *)boldSystemFontOfSize:(CGFloat)fontSize;  粗体
    + (UIFont *)italicSystemFontOfSize:(CGFloat)fontSize;  斜体

  • 相关阅读:
    Chapter 8. 面向对象(类库、委托)
    Chapter 8. 面向对象(多态--接口)
    练习:C# -- 多态
    Chapter 8. 面向对象(多态--抽象类)
    Chapter 8. 面向对象(多态--虚方法)
    Chapter 8. 面向对象(继承)
    Chapter 8. 面向对象(封装)
    Chapter 8. 面向对象(类、对象、字段、方法、属性、构造函数)
    练习、C# 结构体、冒泡排序
    1月19日(HTML之旅) CSS样式表
  • 原文地址:https://www.cnblogs.com/jingdizhiwa/p/5613801.html
Copyright © 2020-2023  润新知