iOS实现@功能,有问题欢迎大家指教
第一步 判断什么时候 需要判断最后一个字符是@
NSString *lang = [[UITextInputModecurrentInputMode]primaryLanguage];
if([langisEqualToString:@"zh-Hans"]){//简体中文输入,包括简体拼音,健体五笔,简体手写
UITextRange *selectedRange = [self.textViewmarkedTextRange];
UITextPosition *position = [self.textViewpositionFromPosition:selectedRange.startoffset:0];
if (!position){//非高亮
[selfconfig:x];
}
}else{//中文输入法以外
[selfconfig:x];
}
- (void)config:(NSString *)text
{
if (!text.length) {
return;
}
NSString *lastString = [textsubstringFromIndex:text.length-1];
NSString *textString = [textsubstringToIndex:text.length-1];//除@之外的字符
if ([lastStringisEqualToString:@"@"]) {
@weakify(self);
[[selfgetText]subscribeNext:^(id x) {
@strongify(self);
NSMutableAttributedString *attribute = [[NSMutableAttributedStringalloc]initWithAttributedString:self.textView.attributedText];
[attribute deleteCharactersInRange:NSMakeRange(textString.length,1)];
NSTextAttachment *imageText = [[NSTextAttachmentalloc]init];
imageText.image = [selfgetImage:[NSStringstringWithFormat:@"@%@",x]];
NSAttributedString * attStr = [NSAttributedStringattributedStringWithAttachment:imageText];
//[attribute insertAttributedString:attStr atIndex:textString.length];
[attribute appendAttributedString:attStr];
dispatch_async(dispatch_get_main_queue(), ^{
[self.textViewsetAttributedText:attribute];;
});//@@@@ @@@
}];
}
}
//这一步主要是为了获取@后的字符,我这是写的一个测试例子
- (RACSignal *)getText
{
return [RACSignalstartEagerlyWithScheduler:[RACSchedulerscheduler]block:^(id<RACSubscriber> subscriber) {
[subscriber sendNext:@"李三"];
[subscriber sendCompleted];
}];
}
- (UIImage *)getImage:(NSString *)name
{
UIColor *color = [UIColorclearColor];
CGRect rect =CGRectMake(0.0f,0.0f,50,13);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context =UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [colorCGColor]);
CGContextFillRect(context, rect);
UIImage *img =UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSString *headerName = name;
UIImage *headerimg = [selfimageToAddText:imgwithText:headerName];
return headerimg;
}
//把文字绘制到图片上
- (UIImage *)imageToAddText:(UIImage *)img withText:(NSString *)text
{
//1.获取上下文
UIGraphicsBeginImageContext(img.size);
//2.绘制图片
[img drawInRect:CGRectMake(0,0, img.size.width,13)];
//3.绘制文字
// CGRect rect = CGRectMake(0,(img.size.height-45)/2, img.size.width, 25);
CGRect rect =CGRectMake(0,0, img.size.width,13);
NSMutableParagraphStyle *style = [[NSMutableParagraphStyledefaultParagraphStyle]mutableCopy];
style.alignment =NSTextAlignmentCenter;
//文字的属性
NSDictionary *dic =@{NSFontAttributeName:[UIFontsystemFontOfSize:12],NSParagraphStyleAttributeName:style,NSForegroundColorAttributeName:[UIColorredColor]};
//将文字绘制上去
[text drawInRect:rectwithAttributes:dic];
//4.获取绘制到得图片
UIImage *watermarkImg =UIGraphicsGetImageFromCurrentImageContext();
//5.结束图片的绘制
UIGraphicsEndImageContext();
return watermarkImg;
}
有问题,欢迎评论指教,谢谢大家的支持!!!