gpt4 book ai didi

ios - 使用 UIDocumentPickerViewController 在 Swift 中导入文本

转载 作者:搜寻专家 更新时间:2023-10-30 22:05:13 28 4
gpt4 key购买 nike

我目前正在学习 iOS 开发类(class),作为我项目的一部分,我的任务是使用 UIDocumentPickerViewController 导入文本。我发现的每个示例要么 a) 用 Objective-C 编写,要么 b) 用于导入 UIImage 文件。

如何为文本文件设置委托(delegate)方法?

这是我到目前为止所得到的:

我已经设置了 iCloud 功能。 有效

指定委托(delegate),如下:

class MyViewController: UIViewController, UITextViewDelegate, UIDocumentPickerDelegate

我已经为我要导入的文本类型设置了属性:

@IBOutlet weak var newNoteBody: UITextView!

我有一个 IBAction 设置如下:

@IBAction func importItem(sender: UIBarButtonItem) {

var documentPicker: UIDocumentPickerViewController = UIDocumentPickerViewController(documentTypes: [kUTTypeText as NSString], inMode: UIDocumentPickerMode.Import)
documentPicker.delegate = self
documentPicker.modalPresentationStyle = UIModalPresentationStyle.FullScreen
self.presentViewController(documentPicker, animated: true, completion: nil)

}

我不知道下面应该是什么行。 Apple 网站上的文档不清楚,我发现的每个示例都是 Objective-C 或图像。

// MARK: - UIDocumentPickerDelegate Methods

func documentPicker(controller: UIDocumentPickerViewController, didPickDocumentAtURL url: NSURL) {
if controller.documentPickerMode == UIDocumentPickerMode.Import {
// What should be the line below?
self.newNoteBody.text = UITextView(contentsOfFile: url.path!)
}
}

最佳答案

明白了!我有两个问题:

1) Apple 说您必须在数组中指定 UTI。我将 documentType 称为 KUTTypeText。它应该是数组中的 "public.text"

这是 Apple 的列表 Uniform Text Identifiers (UTIs)

@IBAction func importItem(sender: UIBarButtonItem) {

var documentPicker: UIDocumentPickerViewController = UIDocumentPickerViewController(documentTypes: ["public.text"], inMode: UIDocumentPickerMode.Import)
documentPicker.delegate = self
documentPicker.modalPresentationStyle = UIModalPresentationStyle.FullScreen
self.presentViewController(documentPicker, animated: true, completion: nil)

}

第二个问题是 Delegate 的句法问题,解决方法如下:

// MARK: - UIDocumentPickerDelegate Methods

func documentPicker(controller: UIDocumentPickerViewController, didPickDocumentAtURL url: NSURL) {
if controller.documentPickerMode == UIDocumentPickerMode.Import {
// This is what it should be
self.newNoteBody.text = String(contentsOfFile: url.path!)
}
}

关于ios - 使用 UIDocumentPickerViewController 在 Swift 中导入文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28641325/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com