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

Xamarin移植Swift代码:找不到接收NSAttributedString的NSTextStorage构造方法

解决Xamarin.iOS中NSTextStorage初始化问题

嘿,我明白你在移植Swift代码到Xamarin时遇到的困惑了!在Xamarin.iOS的绑定中,确实没有直接提供接收NSAttributedString作为参数的NSTextStorage构造函数,但我们可以通过两步操作实现和Swift代码完全相同的效果:

  • 首先创建一个空的NSTextStorage实例
  • 然后将目标NSAttributedString设置为它的内容

下面是对应的C#代码示例:

// 先做null检查,替代Swift里的强制解包,避免空引用异常
if (this.AttributedText == null)
{
    throw new InvalidOperationException("AttributedText cannot be null");
}

// 初始化空的NSTextStorage
var textStorage = new NSTextStorage();
// 设置对应的富文本内容,这一步等效于Swift的构造初始化
textStorage.SetString(this.AttributedText);

如果你想更简洁,也可以合并成一行(但还是建议保留null检查,避免潜在的空引用问题):

var textStorage = new NSTextStorage();
textStorage.SetString(this.AttributedText ?? new NSAttributedString());

这种方式和你原来的Swift代码NSTextStorage(attributedString: self.attributedText!)功能完全一致,都是将指定的富文本内容加载到NSTextStorage中。

内容的提问来源于stack exchange,提问作者Drunken Daddy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:48:12