如何在viewWillDisappear上清除/清空粘贴板

时间:2012-06-16 22:30:55

标签: ios cocoa-touch uitextview uipasteboard

我使用UIPasteboard在两个UITextView之间复制/粘贴文字。

代码如下所示:

- (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:@""]; 
}

3 个答案:

答案 0 :(得分:20)

iOS - UIPasteboard

尝试以下方法:

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

Arab_Geek的回答是正确的但可用于Cocoa(我怀疑你正在寻找iOS解决方案)

答案 1 :(得分:3)

OS X - NSPasteboard

你去..

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

答案 2 :(得分: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)恢复状态。