2012-06-16 28 views
6

我使用UIPasteboard在兩個UITextView之間複製/粘貼文本。如何在viewWillDisappear上清除/清空粘貼板

代碼如下所示:

- (void)viewDidLoad { 
    [super viewDidLoad]; 
    pasteBoard = [UIPasteboard generalPasteboard]; //it is declared in .h as UIPasteboard *pasteBoard; 
} 

-(IBAction)doCopyBtn { 
    if (![toCopyTextView.text isEqualToString:@""]){ 
     pasteBoard.string = toCopyTextView.text; 
     NSLog(@"pasteb1 %@", pasteBoard.string); 
    } else { 
     NSLog (@"error! enter smth"); 
    } 
} 

-(IBAction)doPasteBtn { 
    if (![pasteBoard.string isEqualToString:@""]){ 
     toPasteTextView.text = pasteBoard.string; 
     NSLog(@"pasteb2 %@", pasteBoard.string); 
    } else { 
     NSLog (@"error! enter smth"); 
    } 
} 

即使這不能幫助(的NSLog返回:pasteb2 (null)

-(void) viewWillDisappear:(BOOL)animated{ 
    [super viewWillDisappear:animated]; 
    [pasteBoard setString:@""]; 
} 

回答

19

iOS版 - UIPasteboard

嘗試以下操作:

UIPasteboard *pb = [UIPasteboard generalPasteboard]; 
    [pb setValue:@"" forPasteboardType:UIPasteboardNameGeneral]; 

Arab_Geek的反應是正確的,但可用於可可(我懷疑你正在尋找的是iOS溶液)

+0

非常感謝! –

+1

感謝您的回答。如果有人想要一個醜陋的長單行:'[[UIPasteboard generalPasteboard] setValue:@「」forPasteboardType:UIPasteboardNameGeneral];' –

3

OS X - NSPasteboard

在這裏,你去..

NSPasteboard *pb = [NSPasteboard generalPasteboard]; 
[pb declareTypes: [NSArray arrayWithObject:NSStringPboardType] owner: self]; 
[pb setString: @"" forType: NSStringPboardType]; 
+0

不幸的是它誤解了「NSStringPboardType」。另外,NSPasteboard不存在。 –

+0

@ Sheonna8 #import < - 將此添加到您的.m文件中 –

+0

trued,寫入找不到(我也試圖找到框架 - 不成功) –

2

將該值設置爲""會爲所有預期目的返回nil。但是,它會使粘貼板處於與粘貼操作之前稍微不同的狀態。

斯威夫特

let pb = self.pasteBoard() 
pb.setValue("", forPasteboardType: UIPasteboardNameGeneral) 

...不等同於UIPasteboard.removePasteboardWithName()。如果恢復UIPasteboard狀態令人擔憂(1),可以使用以下塊:

斯威夫特

let pb = self.pasteBoard() 

let items:NSMutableArray = NSMutableArray(array: pb.items) 
for object in pb.items { 
    if let aDictionary = object as? NSDictionary { 
     items.removeObject(aDictionary) 
    } 
} 
pb.items = items as [AnyObject] 

(1)中恢復狀態。