NSTextAttachment的简单图文混排

目标界面是这样的

164955_XPZZ_574245.png

上边是一个输入框的textview,下面两个表情是两个按钮,点击了就把对应的表情添加到输入框里。所以textview有对应的IBOutlet属性,按钮只有对应的点击事件。

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UITextView *mulTextView;

- (IBAction)addFace:(UIButton *)sender;

@end

NSTextAttachment有两个属性,一个是image,用来指定图片,一个是bounds,用来指定宽高。

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 指定换行方式
    NSMutableAttributedString* textAttStr = [[NSMutableAttributedString alloc] initWithString:_mulTextView.text];
    NSMutableParagraphStyle* linebreak = [[NSMutableParagraphStyle alloc]init];
    linebreak.lineBreakMode = NSLineBreakByCharWrapping;
    
    [textAttStr addAttribute:(NSString*)NSParagraphStyleAttributeName  value:(id)linebreak range:NSMakeRange(0, textAttStr.length)];
    
    _mulTextView.attributedText = textAttStr;
    
}

- (IBAction)addFace:(UIButton *)sender {
    
    NSTextAttachment* face = [[NSTextAttachment alloc] initWithData:nil ofType:nil];
    
    if (sender.tag == 1001) {
        
        face.image = [UIImage imageNamed:@"z001.png"];
        
    } else {
        
        face.image = [UIImage imageNamed:@"z002.png"];
        
    }
    
    face.bounds = CGRectMake(0, 0, 20, 20);
    
    NSAttributedString* faceAttStr = [NSAttributedString attributedStringWithAttachment:face];
    
    NSMutableAttributedString* textAttStr = [_mulTextView.attributedText mutableCopy];
    [textAttStr insertAttributedString:faceAttStr atIndex:_mulTextView.selectedRange.location];
    
    _mulTextView.attributedText = textAttStr;
    
}

@end

看一下结果截图

170049_nEKg_574245.png

转载于:https://my.oschina.net/u/574245/blog/661854

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值