Nono
Nono

Reputation: 251

Cocoa/Obj-C - TextField to clipboard button

Got 1 UITextField and 1 button. There is text in my textfield, and when we click on the button, the text is copied to the OSX clipboard.

How can I do that? I've readed the NSPastboard Class Reference but didn't understand how to do that -simply-

Got my button defined in my AppControler.h like this:

- (IBAction)copyButton:(id)sender;

What am I supposed to write in my AppControler.m? My textfield is called "descTextField"

Upvotes: 6

Views: 3382

Answers (3)

Murad Javed
Murad Javed

Reputation: 1

Hope this will work for you.

    - (IBAction)copyToClipboardActionBtn:(id)sender {
        UIPasteboard *pasteBoard = [UIPasteboard generalPasteboard];
        [pasteBoard setString: _descTextField.text];
    }

Upvotes: 0

martn_st
martn_st

Reputation: 2636

according to apple's doc / guide i think it should be rather like this:

- (IBAction)copyButton:(id)sender {
    NSPasteboard *pasteBoard = [NSPasteboard generalPasteboard]; 
    [pasteBoard clearContents];
    [pasteBoard writeObjects:@[[textField stringValue]]];
}

Upvotes: 0

Max
Max

Reputation: 16719

- (IBAction)copyButton:(id)sender {
   NSPasteboard *pasteBoard = [NSPasteboard generalPasteboard];
   [pasteBoard declareTypes:[NSArray arrayWithObjects:NSStringPboardType, nil] owner:nil];
   [pasteBoard setString: [textField stringValue] forType:NSStringPboardType];
}

Upvotes: 19

Related Questions