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

如何正确使用iOS 13新增的insertTextPlaceholder?

解决iOS 13+中TextView的insertTextPlaceholder不显示问题

嘿,我刚帮你捋了下这个问题——你用insertTextPlaceholder(with:)没看到占位符,核心原因是这个方法只创建了一个占位符的“容器”,但你没给它填充内容,也没开启必要的编辑属性!

下面是正确的使用步骤和完整代码示例:

关键注意点

  • 必须给生成的NSTextPlaceholder对象设置文本内容(普通字符串或富文本),不然它就是个透明容器,完全看不见
  • 要确保你的TextView开启了allowsEditingTextAttributes属性,因为文本占位符属于富文本编辑功能的一部分,默认这个属性是false

完整代码示例

if #available(iOS 13.0, *) {
    // 1. 先准备占位符的文本和样式
    let placeholderContent = "请输入你的消息..."
    let placeholderStyle: [NSAttributedString.Key: Any] = [
        .foregroundColor: UIColor.lightGray,
        .font: UIFont.systemFont(ofSize: 16)
    ]
    let attributedPlaceholder = NSAttributedString(string: placeholderContent, attributes: placeholderStyle)
    
    // 2. 插入占位符容器并赋值内容
    let textPlaceholder = msgBox.insertTextPlaceholder(with: CGSize(width: 210, height: 40))
    textPlaceholder.attributedString = attributedPlaceholder
    
    // 3. 开启TextView的富文本编辑权限
    msgBox.allowsEditingTextAttributes = true
    
    // 可选:如果TextView初始为空,确保占位符显示在开头位置
    msgBox.becomeFirstResponder()
}

额外避坑提示

  • 如果TextView已有文本内容,占位符会插入到当前光标位置,可能被原有文本遮挡,确保初始时TextView的text为空
  • 占位符的尺寸要合理,比如高度不能小于字体的行高,不然文本会被截断显示不出来
  • 如果你不需要自定义尺寸,也可以用insertTextPlaceholder()方法,它会自动根据文本内容计算合适的尺寸

内容的提问来源于stack exchange,提问作者Utku Dalmaz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 14:52:29