目标界面是这样的app
上边是一个输入框的textview,下面两个表情是两个按钮,点击了就把对应的表情添加到输入框里。因此textview有对应的IBOutlet属性,按钮只有对应的点击事件。atom
@interface ViewController () @property (weak, nonatomic) IBOutlet UITextView *mulTextView; - (IBAction)addFace:(UIButton *)sender; @end
NSTextAttachment有两个属性,一个是image,用来指定图片,一个是bounds,用来指定宽高。code
@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
看一下结果截图
事件