首页 > 解决方案 > 如何知道何时从 Objective-C 中的特定文本字段复制文本?

问题描述

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

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

标签: iosobjective-cuitextfieldtouch

解决方案


您可以实现该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

推荐阅读