car*_*196 31
这是我用来检测UITextView中的粘贴事件:
// Set this class to be the delegate of the UITextView. Now when a user will paste a text in that textview, this delegate will be called.
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
// Here we check if the replacement text is equal to the string we are currently holding in the paste board
if ([text isEqualToString:[UIPasteboard generalPasteboard].string]) {
// code to execute in case user is using paste
} else {
// code to execute other wise
}
return YES;
}
Run Code Online (Sandbox Code Playgroud)
jos*_*ine 14
您的UITextView将调用其UITextViewDelegate方法
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
Run Code Online (Sandbox Code Playgroud)
如果已设置代表.当在键盘上键入字符时以及将文本粘贴到文本视图中时,都会调用此方法.粘贴的文本是replacementText参数.
Tak*_*ori 14
if string == UIPasteboard.general.string如果在粘贴板中有长句,则检查粘贴板的字符串需要几秒钟.用户看到键盘在此检查时被冻结.我的解决方案是检查新字符的长度是否大于1.如果长度大于1,则字符串来自粘贴板.
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if string.characters.count > 1{
//User did copy & paste
}else{
//User did input by keypad
}
return true
}
Run Code Online (Sandbox Code Playgroud)
正常工作的完美Xcode 9.4 Swift 4.1
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if text.contains(UIPasteboard.general.string ?? "") {
return false
}
return true
}
Run Code Online (Sandbox Code Playgroud)
每当用户尝试粘贴到文本字段时,if条件都会执行。
此代码将停止粘贴
适用于 Swift5.1
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if let paste = UIPasteboard.general.string, text == paste {
print("paste")
} else {
print("normal typing")
}
return true
}
Run Code Online (Sandbox Code Playgroud)
在 iOS 14 中,每次应用程序从中获取值时都会触发通知,UIPasteboard.general.string
因此检测用户是否粘贴某些内容的正确方法是覆盖paste(_)函数:
var isPastingContent = false
open override func paste(_ sender: Any?) {
isPastingContent = true
super.paste(sender)
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if isPastingContent {
// do something
}
isPastingContent = false
}
Run Code Online (Sandbox Code Playgroud)
尝试子类 UITextview,并覆盖此功能。
public override func paste(_ sender: Any?)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18094 次 |
| 最近记录: |