如何编辑复制到UIPasteboard的文本 [英] How can I edit the text copied into UIPasteboard
本文介绍了如何编辑复制到UIPasteboard的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试处理用户从UILabel复制到UIPasteboard的文本,但是找不到示例.
I am trying to manipulate the text the user copied from a UILabel into the UIPasteboard but can't find an example.
推荐答案
这里是您要实现的功能的完整示例视图控制器(请阅读评论以了解发生了什么...):
Here is a full sample view controller for what you are trying to achieve (read the comments to understand what is going on...):
import UIKit
import MobileCoreServices
class ViewController: UIViewController {
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// add an observer (self) for whenever the pasteboard contents change
// this is going to be called whenever the user copies text for example
NSNotificationCenter
.defaultCenter()
.addObserver(
self,
selector: "pasteboardChanged:",
name: UIPasteboardChangedNotification,
object: nil)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
// make sure to pair addition/removal of observers
// we add the observer in viewWillAppear:, so let's
// remove it in viewWillDisappear: (here)
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// this will be called whenever the pasteboard changes
// we specified this function in our observer registration above
@objc private func pasteboardChanged(notification: NSNotification){
// this is what the user originally copied into the pasteboard
let currentPasteboardContents = UIPasteboard.generalPasteboard().string
// you can now modify whatever was copied
let newPasteboardContent = " ----- MODIFY THE PASTEBOARD CONTENTS (\(currentPasteboardContents)) AND SET THEM HERE ---------"
// before we can actually set the new pasteboard contents, we need to make
// sure that this method isn't called recursively (we will change the pasteboard's
// contents, so if we don't remove ourselves from the observer, this method will
// be called over and over again, ending up leaving us in an endless loop)
NSNotificationCenter
.defaultCenter()
.removeObserver(
self,
name: UIPasteboardChangedNotification,
object: nil)
// GREAT! We unregistered ourselves as an observer, now's the time
// to change the pasteboard contents to whatever we want!
UIPasteboard.generalPasteboard().string = newPasteboardContent
// we want to get future changes to the pasteboard, so let's re-add
// ourselves as an observer
NSNotificationCenter
.defaultCenter()
.addObserver(
self,
selector: "pasteboardChanged:",
name: UIPasteboardChangedNotification,
object: nil)
}
}
确保您import MobileCoreServices
,否则您将无法使用某些代码...
Make sure you import MobileCoreServices
otherwise you won't be able to use some of the code...
祝你好运!
如果您想走一条不太"hacky"的路线,建议您使用UIMenuController
.此处有一个不错的教程/指南:
If you'd like to go a less "hacky" route, I'd suggest you tap into UIMenuController
. There is a nice tutorial/guide here:
这篇关于如何编辑复制到UIPasteboard的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文