单击按钮后移动图像

时间:2012-03-16 18:55:52

标签: objective-c interface

我以编程方式在xCode中插入自定义按钮(图像)。点击UI按钮后,我想将按钮移动到iPhone屏幕上的自定义位置。

以编程方式按钮:

self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];

    UIButton *MyButton = [UIButton buttonWithType:nil];

    MyButton.frame = CGRectMake(100, 170, 100, 30);

    [MyButton setImage:[UIImage imageNamed:@"tap.png"] forState:nil];

    [self.view addSubview:MyButton];

    [MyButton addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside];

我试图在点击后移动按钮。

-(void)buttonPressed {
    NSLog(@"Button Pressed!");


    CGRect frame = MyButton.frame;
    frame.origin.x = 100; // new x coordinate
    frame.origin.y = 4; // new y coordinate

    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration: 0.1];
    MyButton.frame = frame;
    [UIView commitAnimations];

    }

但没有任何事情发生。

我是.h档案

IBOutlet UIButton *MyButton;
@property (nonatomic, retain) UIButton *MyButton;

1 个答案:

答案 0 :(得分:0)

使用UIButton会更容易,因为他们已经在监听点击事件。否则,您需要在UIImageView中添加UIGestureRecognizer。在Interface Builder中设置UIButton并连接到IBOutlet后,您可以使用相同的代码移动它。

修改

您的问题可能是您正在创建一个新按钮,而不是分配给您的MyButton属性。而不是:

UIButton *MyButton = [UIButton buttonWithType:nil];

尝试:

MyButton = [UIButton buttonWithType:UIButtonTypeCustom]; // UIButtonTypeCustom is what you would need to properly display your image. If you aren't setting an image for the button yet, then instead try UIButtonTypeRoundedRect.