【问题标题】:Get text from NSTextView in Swift在 Swift 中从 NSTextView 获取文本
【发布时间】:2019-09-05 19:29:49
【问题描述】:

我有一个 NSTextView,用户可以在其中输入文本。我使用它而不是 NSTextField,因为我需要它来支持在用户按 Enter 时添加新行(这似乎不适用于 NSTextField,但它适用于 NSTextView)

我这辈子都不知道如何从 NSTextView 中取出所有文本。

这个 SO 答案告诉我如何在 Objective-C 中做到这一点:

How to find the text in an NSTextView?

但我很难跳到 Swift。如果我尝试将 textStorage 属性强制转换为 NSAttributedString,我会收到错误“无法将表达式类型 NSTextStorage? 转换为 NSAttributedString 类型”。

这是一个 OSX 应用程序,而不是 iPhone 应用程序,如果这有什么不同的话。

提前感谢您的帮助。

【问题讨论】:

    标签: swift macos


    【解决方案1】:

    我在施法时忘记了感叹号。我需要这样做:(NSTextView 的名称是 txtPhoneNumbers)

        (txtPhoneNumbers.textStorage as NSAttributedString!).string
    

    【讨论】:

      【解决方案2】:

      斯威夫特 5

      获取 NSTextView 字符串的简单解决方案。

      if let str = textView.textStorage?.string {
          // do something with string
      }
      

      【讨论】:

        猜你喜欢
        • 2017-10-22
        • 2017-03-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多