Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

16. Documents and Data Sharing > Recipe: Passively Updating the Pasteboard

Recipe: Passively Updating the Pasteboard

iOS selection and copy interface are not, frankly, the most streamlined elements of the operating system. There are times when you want to simplify matters for your user while preparing content that’s meant to be shared to other applications. Consider Recipe 16-1. It allows the user to use a local editor to enter and edit text, while automating the process of updating the pasteboard. When the watcher is active (toggled by a simple button tap), the text is sent to the pasteboard on each edit. This is accomplished by implementing a text view delegate method (textViewDidChange:) that responds to edits by automatically assigning those changes to the pasteboard (updatePasteboard).

Recipe 16-1. Creating an Automatic Text-Entry to Pasteboard Solution


@implementation TestBedViewController
- (void) updatePasteboard
{
   // Copy the text to the pasteboard when the watcher is enabled
    if (enableWatcher)
        [UIPasteboard generalPasteboard].string = textView.text;
}

- (void)textViewDidChange:(UITextView *)textView
{
    // Delegate method calls for an update
    [self updatePasteboard];
}

- (void) toggle: (UIBarButtonItem *) bbi
{
    // switch between standard and auto-copy modes
    enableWatcher = !enableWatcher;
    bbi.title = enableWatcher ? @"Stop Watching" : @"Watch";
}

- (void) loadView
{
    [super loadView];

    // Build a text view and set the delegate to self
    textView = [[UITextView alloc] initWithFrame:CGRectZero];
    textView.font = [UIFont fontWithName:@"Futura"
        size: IS_IPAD ? 32.0f : 16.0f];
    textView.delegate = self;
    [self.view addSubview:textView];

    // Add a toggle button
    self.navigationItem.rightBarButtonItem =
        BARBUTTON(@"Watch", @selector(toggle:));
}

- (void) viewDidAppear:(BOOL)animated
{
    // Always perform an update whenever the view appears
    textView.frame = self.view.bounds;
    [self updatePasteboard];
}

- (void) didRotateFromInterfaceOrientation:
    (UIInterfaceOrientation)fromInterfaceOrientation
{
    // Update presentation
    [self viewDidAppear:NO];
}
@end



Get This Recipe’s Code

To get the code used for this recipe, go to https://github.com/erica/iOS-5-Cookbook, or if you’ve downloaded the disk image containing all the sample code from this book, go to the folder for Chapter 16 and open the project for this recipe.


  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint