简体   繁体   English

从Swift中的NSTextView获取文本

[英]Get text from NSTextView in Swift

I have an NSTextView that users will type text into. 我有一个NSTextView,用户将输入文本。 I am using this instead of an NSTextField because I need it to support adding a new line when the user hits enter (This doesn't seem to work with NSTextField, but it does with NSTextView) 我使用它而不是NSTextField因为我需要它来支持在用户点击输入时添加新行(这似乎不适用于NSTextField,但它与NSTextView一起使用)

I can't for the life of me figure out how to get all the text out of the NSTextView. 我不能为我的生活弄清楚如何从NSTextView中获取所有文本。

This SO answer tells me how to do it in Objective-C: 这个SO答案告诉我如何在Objective-C中做到这一点:

How to find the text in an NSTextView? 如何在NSTextView中查找文本?

But I'm having a hard time making the jump to Swift. 但是我很难跳到Swift。 If I try to cast the textStorage property to NSAttributedString, I get the error "Cannot convert the expression type NSTextStorage? to type NSAttributedString". 如果我尝试将textStorage属性强制转换为NSAttributedString,我会收到错误“无法将表达式类型NSTextStorage转换为类型NSAttributedString”。

This is an OSX application, not an iPhone application, if that makes any difference for some reason. 这是一个OSX应用程序,而不是iPhone应用程序,如果由于某种原因产生任何差异。

Thanks in advance for the help. 在此先感谢您的帮助。

I was forgetting the exclamation point when casting. 我在铸造时忘记了惊叹号。 I needed to do this: (the name of the NSTextView is txtPhoneNumbers) 我需要这样做:( NSTextView的名称是txtPhoneNumbers)

    (txtPhoneNumbers.textStorage as NSAttributedString!).string

Swift 5 斯威夫特5

A simple solution to getting the string of an NSTextView. 获取NSTextView字符串的简单解决方案。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM