You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在allowsEditingTextAttributes为NO时启用系统表情键盘的Memoji贴纸?

解决方案:在allowsEditingTextAttributes=NO的UITextView中显示并插入Memoji贴纸

当allowsEditingTextAttributes设为NO时,UITextView会告知系统仅支持纯文本输入,导致系统键盘隐藏Memoji贴纸入口。要解决这个问题,我们可以通过自定义UITextView子类,接管输入逻辑并手动处理Memoji贴纸的插入,同时保持属性编辑限制。

实现步骤

  1. 创建UITextView子类,重写输入处理方法
    系统选择Memoji贴纸后,会将其以NSAttributedString形式存入粘贴板,我们可以拦截输入操作,手动读取粘贴板内容并插入到文本中。
@interface CustomMemojiTextView : UITextView
@end

@implementation CustomMemojiTextView

- (void)insertText:(NSString *)text {
    // 检查粘贴板是否存在Memoji富文本
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    if (pasteboard.attributedString && pasteboard.attributedString.length > 0) {
        // 获取当前光标位置
        UITextRange *selectedRange = self.selectedTextRange;
        NSInteger insertionIndex = [self offsetFromPosition:self.beginningOfDocument toPosition:selectedRange.start];
        
        // 构建新的富文本并插入
        NSMutableAttributedString *newAttrText = [self.attributedText mutableCopy];
        [newAttrText insertAttributedString:pasteboard.attributedString atIndex:insertionIndex];
        
        // 直接设置富文本(allowsEditingTextAttributes=NO不影响代码层面的属性设置)
        self.attributedText = newAttrText;
        
        // 移动光标到插入后的位置
        UITextPosition *newPos = [self positionFromPosition:self.beginningOfDocument offset:insertionIndex + pasteboard.attributedString.length];
        self.selectedTextRange = [self textRangeFromPosition:newPos toPosition:newPos];
        
        // 清空粘贴板避免重复插入
        [pasteboard setAttributedString:nil];
        return;
    }
    
    // 处理普通文本输入
    [super insertText:text];
}

// 允许粘贴富文本(Memoji贴纸通过粘贴流程插入)
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    if (action == @selector(paste:)) {
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        return pasteboard.attributedString != nil;
    }
    return [super canPerformAction:action withSender:sender];
}

@end
  1. 使用自定义子类替换原UITextView
    在代码中初始化自定义TextView,保持allowsEditingTextAttributes=NO的同时,确保键盘类型为默认值(支持Memoji显示):
CustomMemojiTextView *textView = [[CustomMemojiTextView alloc] initWithFrame:CGRectMake(0, 0, 300, 300)];
textView.delegate = self;
textView.allowsEditingTextAttributes = NO;
textView.keyboardType = UIKeyboardTypeDefault; // 确保使用默认键盘类型,支持Memoji入口
[self.view addSubview:textView];

关键说明

  • allowsEditingTextAttributes=NO仅限制用户通过界面编辑文本属性(如字体、颜色),代码层面直接设置attributedText是完全允许的。
  • 系统键盘显示Memoji贴纸的前提是输入控件支持默认键盘类型,不要将keyboardType设置为纯文本类型(如UIKeyboardTypeASCIICapable)。
  • 该方案通过拦截粘贴板内容实现Memoji插入,完全复用系统键盘的Memoji选择界面,无需自定义UI。

内容的提问来源于stack exchange,提问作者白瑜颖

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 20:22:27