【问题标题】:How to know when text is copied from a specific textfield in Objective-C?如何知道何时从 Objective-C 中的特定文本字段复制文本?
【发布时间】:2019-10-14 19:01:37
【问题描述】:

我有一些可编辑的文本字段。当用户选择其文本时,会显示复制和粘贴菜单项。
我想知道用户何时点击副本。因为我想更改复制的文本。
有可能吗?

更多详情: 我想更改 3 个文本字段的副本。当复制其中一个文本字段时,我想将所有这 3 个文本字段文本连接到剪贴板。此页面中还有其他文本字段,但我不想为它们做任何事情。

【问题讨论】:

  • @Andreas 谢谢。但我的起点有问题。我想在用户点击副本时收到通知,但我找不到解决方案。
  • 请附上你目前研究的内容

标签: ios objective-c uitextfield touch


【解决方案1】:

您可以实现copy() 方法来“拦截”复制操作并修改放置在剪贴板上的内容。

最简单的方法可能是UITextField的简单子类:

//
//  MyTextField.h
//
//  Created by Don Mag on 5/29/19.
//

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface MyTextField : UITextField

@end

NS_ASSUME_NONNULL_END

//
//  MyTextField.m
//
//  Created by Don Mag on 5/29/19.
//

#import "MyTextField.h"

@implementation MyTextField

- (void)copy:(id)sender {

    // debugging
    NSLog(@"copy command selected");

    // get the selected range
    UITextRange *textRange = [self selectedTextRange];

    // if text was selected
    if (textRange) {

        // get the selected text
        NSString *selectedText = [self textInRange:textRange];

        // change it how you want
        NSString *modifiedText = [NSString stringWithFormat:@"Prepending to copied text: %@", selectedText];

        // get the general pasteboard
        UIPasteboard *pb = [UIPasteboard generalPasteboard];

        // set the modified copied text to the pasteboard
        pb.string = modifiedText;
    }

}

@end

【讨论】:

    【解决方案2】:

    您可以从剪贴板获取复制的字符串并在粘贴前更新到剪贴板。

    NotificationCenter.default.addObserver(self, selector: #selector(clipboardChanged),
                                                   name: UIPasteboard.changedNotification , object: nil)
    
    @objc func clipboardChanged() {
        if let clipboardString = UIPasteboard.general.string as? String {
            // Update string as per your requirement
            let myString = textfield1.text! + " " + textfield2.text! + " " + textfield3.text! + " Append String"
            textfield1.text = myString
            textfield2.text = myString
            textfield3.text = myString
            print(myString)
        }
    }
    

    【讨论】:

    • 谢谢。但剪贴板可能会被这 3 个以外的其他文本字段更改。
    • 您能解释一下具体的问题吗?因为这个答案满足了您在此处发布的问题。
    • 很抱歉我的问题没有完成。我更新了它
    • 您能否检查更新的答案!如果它适合您的解决方案
    猜你喜欢
    • 1970-01-01
    • 2011-10-12
    • 1970-01-01
    • 1970-01-01
    • 2022-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多