2011-09-07 61 views
2

我實現在iPhone應用程序拖拽系統。到目前爲止,我設法實現了可拖動按鈕,並且工作正常。這是代碼,我有:拖放無需拆卸的UIButton

首先,我給你的動作按鈕:

[button addTarget:self action:@selector(imageMoved:withEvent:) forControlEvents:UIControlEventTouchDragInside]; 

然後,我創建了阻力:

- (IBAction) imageMoved:(id) sender withEvent:(UIEvent *) event 
{ 
    NSLog(@"moved"); 
    CGPoint point = [[[event allTouches] anyObject] locationInView:self.view]; 
    UIControl *control = sender; 
    control.center = point; 
} 

不過,我想達到的目標被拖動的按鈕不會從它所在的位置移除。所以我想到了一種解決方案,即創建一個類似於第一個按鈕的新按鈕並移動這個新創建的按鈕。但是我在實施這最後一部分時遇到了麻煩。 有什麼幫助嗎?非常感謝!

回答

1
- (IBAction) imageMoved:(id) sender withEvent:(UIEvent *) event { 
    NSLog(@"moved");   

    CGPoint point = [[[event allTouches] anyObject] locationInView:self.view]; 

    if (![self.view viewWithTag:11]) { 

     NSData *archivedData = [NSKeyedArchiver archivedDataWithRootObject:(UIButton*)sender];     

     UIButton *anotherButton =(UIButton*) [NSKeyedUnarchiver unarchiveObjectWithData:archivedData]; 

     anotherButton.tag = 11;  


     UIImage *senderImage=[(UIButton *)sender imageForState:UIControlStateNormal]; 




     CGImageRef cgImage = [senderImage CGImage]; 


     UIImage *copyOfImage = [[UIImage alloc] initWithCGImage:cgImage]; 



     [anotherButton setImage:copyOfImage forState:UIControlStateNormal]; 

     [self.view addSubview:anotherButton]; 
    } 

    [self.view viewWithTag:11].center = point; 
} 
+0

感謝這麼多的響應。這似乎是正確的我所需要的,但不知它拋出異常:' - [UIImage的encodeWithCoder:]:當它到達線無法識別的選擇發送到實例0x6323500':'NSData的* archivedData =的NSKeyedArchiver archivedDataWithRootObject:發件人]' 。你能看到拋出異常的東西嗎? –

+0

ü要求移動的UIButton但你用它來的UIImageView –

+0

更新退房 –

0

要刪除您可以在原點按鈕添加兩個事件,像這樣的限制:

[button addTarget:self action:@selector(imageMoved:withEvent:) forControlEvents:UIControlEventTouchDragInside]; 
[button addTarget:self action:@selector(imageMoved:withEvent:) forControlEvents:UIControlEventTouchDragOutside]; 

這樣,當你退出當前視圖的邊界事件將觸發太(您的按鈕)你就可以將所有新的按鈕都移到超級視圖的旁邊。