在 IOS 应用程序中编辑和保存文本
text editing & saving in IOS app
我有一个 UITextview 通过调用 rtf 文件来显示某些文本。
我想让用户在 UITextView 上编辑文本并将他们所做的更改保存在 rtf 文件中。
有什么方法可以通过更改 UITextView 上的文本来更改 rtf 文件本身吗?
如果您想要一个即输入即保存的问题解决方案:
- 使您的视图控制器符合
UITextViewDelegate
- 将文本视图的
delegate
连接到视图控制器
- 将以下函数添加到您的视图控制器:
// Path to your RTF file
let url = NSBundle.mainBundle().URLForResource("my_document", withExtension: "rtf")!
func textViewDidChange(textView: UITextView) {
let data = try! textView.attributedText.dataFromRange(NSMakeRange(0, textView.attributedText.length), documentAttributes: [NSDocumentTypeDocumentAttribute: NSRTFTextDocumentType])
data.writeToURL(url, atomically: true)
}
这会将每次击键保存到文件中。虽然不知道性能。我还没有在真实的 iPhone 上测试过这个。如果这对设备来说太难了,请考虑在保存之间设置一个时间延迟,或者设置一个 NSTimer
以每 n 秒保存一次。
我有一个 UITextview 通过调用 rtf 文件来显示某些文本。 我想让用户在 UITextView 上编辑文本并将他们所做的更改保存在 rtf 文件中。
有什么方法可以通过更改 UITextView 上的文本来更改 rtf 文件本身吗?
如果您想要一个即输入即保存的问题解决方案:
- 使您的视图控制器符合
UITextViewDelegate
- 将文本视图的
delegate
连接到视图控制器 - 将以下函数添加到您的视图控制器:
// Path to your RTF file
let url = NSBundle.mainBundle().URLForResource("my_document", withExtension: "rtf")!
func textViewDidChange(textView: UITextView) {
let data = try! textView.attributedText.dataFromRange(NSMakeRange(0, textView.attributedText.length), documentAttributes: [NSDocumentTypeDocumentAttribute: NSRTFTextDocumentType])
data.writeToURL(url, atomically: true)
}
这会将每次击键保存到文件中。虽然不知道性能。我还没有在真实的 iPhone 上测试过这个。如果这对设备来说太难了,请考虑在保存之间设置一个时间延迟,或者设置一个 NSTimer
以每 n 秒保存一次。