目標界面是這樣的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
看一下結果截圖
事件