拖放而不删除UIButton

时间:2011-09-07 13:24:31

标签: objective-c ios drag-and-drop

我正在iphone应用程序中实现拖放系统。到目前为止,我设法实现了可拖动按钮,它工作正常。这是我的代码:

首先,我将操作分配给按钮:

[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;
}

但是,我想要实现的是被拖动的按钮不会从它所在的位置移除。所以我想到了一个解决方案,即创建一个类似于第一个按钮的新按钮并移动这个新创建的按钮。但是我在实施这最后一部分时遇到了麻烦。 有帮助吗?非常感谢!

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:0)

要删除限制,您可以在原点按钮上添加两个事件,如下所示:

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

这样,当您退出当前视图(按钮)的边界时,事件也会激活,并且您将能够在超级视图周围移动新按钮。