在我们做编辑框的时候,可能有需要插入表情的操作,但是会发现在添加表情之后,表情之后的再次输入文字的时候,文字内容回到了控件默认字号。所以我们需要在每次插入表情的时候修整字号。
方法一:
``` /// 插入表情 /// /// - Parameters: /// - range: 插入位置 例: textView.selectedRange /// - icon: 表情Icon /// - iconName: 表情中文名 /// - font: 字体(一般插入表情之后,在输入控件中会导致表情后面输入的字体重置,所以需要修正) func expressionInset(_ range:NSRange, _ icon:String, _ iconName:String, _ font:UIFont? = nil) ->NSMutableAttributedString {
let tempStringOne:NSMutableAttributedString = NSMutableAttributedString(attributedString: self) if !icon.isEmpty { let attachment:CWTextAttachment = CWTextAttachment() attachment.icon = icon attachment.iconName = iconName attachment.image = UIImage(named: icon) attachment.bounds = CWExpressionIconBounds_Main let tempStringTwo:NSAttributedString = NSAttributedString(attachment: attachment) tempStringOne.insert(tempStringTwo, at: range.location) // 修整字体属性 if font != nil { tempStringOne.addAttributes([.font : font!, .baselineOffset : 0, (kCTSuperscriptAttributeName as NSAttributedString.Key) : 0], range: NSMakeRange(0, tempStringOne.length)) } } return tempStringOne
} ```
方法二:
``` @interface ViewController ()
@property (nonatomic, strong)CustomTextView *textView;
/// 将字体属性记录成公用的, 然后在每次UITextview的内容将要发生变化的时候,重置一下它的该属性。 @property (nonatomic, strong)NSDictionary *typingAttributes;
@end
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{ textView.typingAttributes = self.typingAttributes; return YES; } ```