Theoretical Basis of iOS copy, cut, and paste

Source: Internet
Author: User
Tags reverse dns

Theoretical Basis of iOS copy, cut, and paste

Introduction

After iPhone OS 3.0, users can copy text, images, or other data on an application and paste it to different locations of the current or other applications. For example, you can copy an address from an email and paste it into the address field of the Contacts program. Currently, UIKitFrameworkInUITextView,UITextField, AndUIWebViewSupports copy, cut, and paste operations. If you want to get this behavior in your application, you can use the objects of these classes or implement them on your own.

However, after iOS7.0, The UIPasteboard changed from sharing to sandbox.,UIPasteboard is normal, but developers start to use it to store identifiers. This problem occurs when they share these identifiers with other apps. One of the tricks is OpenUDID. After iOS7, use + [UIPasteboard pasteboardWithName: create:] and + [UIPasteboard pasteboardWithUniqueName] to create a clipboard, which is visible only to the same app group, making OpenUDID less useful.

The following sections describe the programming interfaces used for copy, cut, and paste operations in UIKit and explain their usage.

Copy, cut, and paste operations

After iPhone OS 3.0, users can copy text, images, or other data on an application and paste it to different locations of the current or other applications. For example, you can copy an address from an email and paste it into the address field of the Contacts program. Currently, UIKitFrameworkInUITextView,UITextField, AndUIWebViewSupports copy, cut, and paste operations. If you want to get this behavior in your application, you can use the objects of these classes or implement them on your own.

The following sections describe the programming interfaces used for copy, cut, and paste operations in UIKit and explain their usage.

Note:For instructions on copying and pasting, seeIPhone Man-Machine Interface GuideIn this document, copy and paste are supported.

Facilities supporting copy-and-paste operations in UIKit

The UIKit framework provides several classes and oneInformal agreementProvides methods and mechanisms for copying, cutting, and pasting operations in applications. The details are as follows:

  • UIPasteboardClass provides the clipboard interface. Clipboard is a protected area for data sharing within an application or between different applications. This class provides methods to read and write data items on the clipboard.

  • UIMenuControllerClass displays an editing menu on the upper and lower sides of the selected copy, cut, and paste objects. The commands on the editing menu can be copied, cut, pasted, selected, and all selected.

  • UIResponderClass declaredcanPerformAction:withSender:Method. The responder class can implement this method to display or remove commands from the editing menu based on the current context.

  • UIResponderStandardEditActionsInformal protocols declare interfaces for processing copy, cut, paste, select, and all selected commands. When you touch a command on the editing menuUIResponderStandardEditActionsThe method is called.

Concept of clipboard

A clipboard is a standardized mechanism for data exchange within an application or between different applications. The most common use of clipboard is to process copy, clipboard, and paste operations:

  • When you select data in an application and select the copy (or cut) menu command, the selected data is placed on the clipboard.

  • When you choose to Paste commands (which can be in the same or different applications), the data on the clipboard will be copied to the current application.

In iPhone OS, the clipboard is also used to support the Find operation. In addition, it can be used to transmit data between different applications through custom URL types (instead of copying, cutting, and pasting commands, for more information about this technique, see the "communication with other applications" section.

In either case, the basic task you perform through the clipboard is to read and write the Clipboard data. Although these tasks are very simple in concept, they shield a lot of important details. The main reason for the complexity is that there may be many data presentation methods, and this complexity Introduces efficiency considerations. The following sections of this article will discuss these and other issues.

Named clipboard

Clipboard may be public or private. The public clipboard is calledSystem clipboardPrivate clipboard is created by the application. Therefore, it is calledApplication clipboard. The clipboard must have a unique name.UIPasteboardTwo system clipboard is defined, each of which has its own name and purpose:

  • UIPasteboardNameGeneralIt is used for cutting, copying, and pasting operations and involves a wide range of data types. You can usegeneralPasteboardClass method to obtainSingle PieceObject.

  • UIPasteboardNameFindUsed for retrieval operations. The current user is (UISearchBar) The string is written to the clipboard, so it can be shared in different applications. You can callpasteboardWithName:create:Class MethodAnd pass in the name parameterUIPasteboardNameFindValue to retrieve objects that represent the search clipboard.

In typical cases, you only need to use the clipboard defined by the system. However, you can alsopasteboardWithName:create:Method to create your own application clipboard. If you callpasteboardWithUniqueNameMethod,UIPasteboardAn application clipboard with a unique name is provided for you. You can usenameAttribute DeclarationTo obtain this name.

Persistent retention of clipboard

You can mark the clipboard as persistent, so that its content continues to exist after the currently used application ends. Non-persistent clipboard is removed after the application is created and exited. The system clipboard is permanently retained, and the application clipboard is not permanently retained by default. Paste the application into the clipboardpersistentSet propertyYESIt can be permanently retained. When the owner program of the persistent clipboard is uninstalled by the user, it is also removed.

Clipboard owner and data items

Finally, the object that stores data on the clipboard is called the clipboard.Owner. Each piece of data put on the clipboard is called a clipboard.Data items. The clipboard can hold one or more data items. Applications can put or get the expected number of data items. For example, if the content selected by the user in the view contains some text and an image, the clipboard allows you to copy the text and image as different data items. Applications that read multiple data items from the clipboard can choose to read only supported data items (such as text, but not images ).

Important:When an application writes data to a clipboard, the data replaces the current content of the clipboard even if it is only a single data item. Although you may useUIPasteboardOfaddItems:But the write method does not add those items to the current content of the clipboard.

 

Data Representation and UTI

Clipboard operations are often performed between different applications. The system does not require the application to know the other party's information, including the types of data that the other party can process. To maximize the potential data sharing capability, the clipboard can retain multiple types of the same data item.Indicates. For example, a rich text editor can provide HTML, PDF, and plain text representation of copied data. A data item on the Clipboard contains all the representations that the application can provide for the data.

Each Type of Clipboard data item usually has a Unique Type Identifier (Unique Type Identifier ). UTI is a string that uniquely identifies a specific data type. UTI provides a common method to identify data types. If you want to support a custom data type, you must create a unique identifier for it. To this end, you can use reverse DNS notation to define the type identification string to ensure its uniqueness. For example, you can usecom.myCompany.myApp.myTypeTo indicate a custom type ID. For more information, seeOverview of unified type identifiers.

As an example, assuming that an application supports selection of rich text and images, it may want to put the selected text of Rich Text and Unicode versions and different representation of the selected image on the clipboard. In this scenario, each representation of each data item is saved with its own data, as shown in 3-3.

Figure 3-3Clipboard and its representation

In general, in order to maximize the potential for sharing, the Clipboard data items should include as many representations as possible.

The reader of the clipboard must find the data type that best suits its own capabilities (if any. Generally, this means selecting the most informative available type. For example, a text editor may provide HTML (Rich Text) and plain text representation for copied data. applications that support rich text should select HTML representation, applications that only support plain text should select plain text representation.

Change count

The change count is a variable that every clipboard has. It increases with the change of the content of each clipboard-especially when data items are added, modified, or removed. The application can check the change count (throughchangeCountAttribute) to determine whether the current data of the clipboard is the same as the data obtained last time. Each time the change count increases, the clipboard sends a notification to the observer interested in the change.

Selection and menu management

Before copying or cutting some content in a view, You must select "some content ". It may be text, an image, a URL, a color, or other types of data, includingCustom object. To copy and paste objects in a custom view, you must manage the selection of objects in the view. If you use a specific touch gesture (such as double-click) to select an object in the view, you must handle the event, that is, record the selection within the Program (cancel the previous selection at the same time ), you may also need to specify a new option in the view. If you can select multiple objects in the view and perform copy, cut, and paste operations, You must select multiple objects.

Note:Touch events and their processing skills are discussed in the "Touch events" section.

When the application determines that the user has requested the edit menu, which may be a selected action, you should perform the following steps to display the menu:

The program list 3-4 demonstrates howtouchesEnded:withEvent:The Edit menu is displayed in the implementation of the method (note that the Code selected for processing is omitted in this example ). In this code snippet, the custom view also sendsbecomeFirstResponderMessage to ensure that you are the first responder in subsequent copy, cut, and paste operations.

Program list 3-4Show edit menu

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *theTouch = [touches anyObject];
 
    if ([theTouch tapCount] == 2  && [self becomeFirstResponder]) {
 
        // selection management code goes here...
 
        // bring up editing menu.
        UIMenuController *theMenu = [UIMenuController sharedMenuController];
        CGRect selectionRect = CGRectMake(currentSelection.x, currentSelection.y, SIDE, SIDE);
        [theMenu setTargetRect:selectionRect inView:self];
        [theMenu setMenuVisible:YES animated:YES];
 
    }
}

The initial menu contains all the commands, so the first responder provides the correspondingUIResponderStandardEditActionsMethod implementation (copy:,paste:). However, before the menu is displayed, the system sendscanPerformAction:withSender:Message. In many cases, the first response is to customize the view itself. In the implementation of this method, the responder examines the given command (transmitted by the first parameterSelectorIndicates whether the current context is applicable. For example, if the selector ispaste:But the clipboard does not have the data that this view can process, the responder should returnNOTo disable the paste command. If the first responder fails to implementcanPerformAction:withSender:Method, or if you do not process a given command, the message will enter the responder chain.

The program list is shown in 3-5canPerformAction:withSender:Method. This implementation first looks for andcopy:,copy:, Andpaste:The selector matches the message and activates or disables the copy, cut, and paste menu commands Based on the selected context. The clipboard content is also considered for the pasting command.

Program list 3-5Conditional activation of menu commands

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    BOOL retValue = NO;
    ColorTile *theTile = [self colorTileForOrigin:currentSelection];
 
    if (action == @selector(paste:) )
        retValue = (theTile == nil) &&
             [[UIPasteboard generalPasteboard] containsPasteboardTypes:
             [NSArray arrayWithObject:ColorTileUTI]];
    else if ( action == @selector(cut:) || action == @selector(copy:) )
        retValue = (theTile != nil);
    else
        retValue = [super canPerformAction:action withSender:sender];
    return retValue;
}

Note that the last MethodelseThe sub-class calls the implementation of the super class, so that the super class has the opportunity to process commands ignored by the sub-class.

Note that operations on a menu command may change the context of other menu commands. For example, when you select all objects in the view, the copy and cut commands should be included in the menu. In this case, although the menu is still visible, the responder can callupdateMethod To make the first respondercanPerformAction:withSender:Called again.

Copy and cut selected content

When you touch the copy or cut command on the editing menu, the system callscopy:Orcut:Method. In general, the first responder-your custom view-will implement these methods, but if not, the message will enter the responder chain in the normal way. Please note that,UIResponderStandardEditActionsInformal agreementThese methods are declared.

Note:BecauseUIResponderStandardEditActionsIs an informal protocol. Any class in an application can implement its methods. However, in order for commands to be passed on the responder chain by default, classes that implement these methods should inherit fromUIResponderClass, and should be installed in the responder chain.

Incopy:Orcut:In the response code of a message, you need to write the objects or data that correspond to the selected content into the clipboard in as many forms as possible. This operation involves the following steps (assuming there is only one Clipboard data item ):

The program list is 3-6copy:Andcut:Method.cut:Method calledcopy:Method, and then remove the selected object from the view and data model. Note,copy:Method pairCustom objectArchive To GetNSDataObject To be passed as a parameter to the clipboardsetData:forPasteboardType:Method.

Program list 3-6Copy and cut operations

- (void)copy:(id)sender {
    UIPasteboard *gpBoard = [UIPasteboard generalPasteboard];
    ColorTile *theTile = [self colorTileForOrigin:currentSelection];
    if (theTile) {
        NSData *tileData = [NSKeyedArchiver archivedDataWithRootObject:theTile];
        if (tileData)
            [gpBoard setData:tileData forPasteboardType:ColorTileUTI];
    }
}
 
- (void)cut:(id)sender {
     [self copy:sender];
     ColorTile *theTile = [self colorTileForOrigin:currentSelection];
 
     if (theTile) {
         CGPoint tilePoint = theTile.tileOrigin;
         [tiles removeObject:theTile];
          CGRect tileRect = [self rectFromOrigin:tilePoint inset:TILE_INSET];
         [self setNeedsDisplayInRect:tileRect];
     }
}
Paste selected content

The system callspaste:Method. In general, the first responder-your custom view-will implement these methods, but if not, the message will enter the responder chain in the normal way.paste:Method inUIResponderStandardEditActionsInformal agreement.

Inpaste:In the response code of a message, you can read the representation supported by the application from the clipboard, and then add the pasted object toData ModelAnd display the new object on the user-specified view position. This operation involves the following steps (assuming there is only a single Clipboard data item ):

Program list 3-7 ispaste:An Implementation instance of the method.cut:Andcopy:The opposite method. The view in the example first checks whether the Clipboard contains the custom representation data that it supports. If yes, it reads the data and adds it to the data model of the application, then, part of the view-currently selected area-is marked as required for re-painting.

Program list 3-7Paste the Clipboard data to the selected position

- (void)paste:(id)sender {
     UIPasteboard *gpBoard = [UIPasteboard generalPasteboard];
     NSArray *pbType = [NSArray arrayWithObject:ColorTileUTI];
     ColorTile *theTile = [self colorTileForOrigin:currentSelection];
     if (theTile == nil && [gpBoard containsPasteboardTypes:pbType]) {
 
        NSData *tileData = [gpBoard dataForPasteboardType:ColorTileUTI];
        ColorTile *theTile = (ColorTile *)[NSKeyedUnarchiver unarchiveObjectWithData:tileData];
         if (theTile) {
             theTile.tileOrigin = self.currentSelection;
             [tiles addObject:theTile];
             CGRect tileRect = [self rectFromOrigin:currentSelection inset:TILE_INSET];
             [self setNeedsDisplayInRect:tileRect];
         }
     }
}
Delete edit menu

Incut:,copy:, Orpaste:After the command is returned, the edit menu is automatically hidden. Use the following code to make it visible:

[UIMenuController setMenuController].menuVisible = YES;

The editing menu may be hidden at any time. For example, when a warning message is displayed or the user touches other areas of the screen, the editing menu will be hidden. If you have some status or screen display that depends on whether the editing menu is displayed, you should listenUIMenuControllerWillHideMenuNotificationAdvertise and perform appropriate actions.

 

Address: http://blog.sina.com.cn/s/blog_45e2b66c010102h9.html

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.