点击按钮后移动图像
问题描述:
我以编程方式在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;
答
这将是更容易使用的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.
哎呀对不起图像是costum的UIButton – Frenck 2012-03-16 19:02:34
你能对你有确切的问题推断?看起来你非常接近。 – FreeAsInBeer 2012-03-16 19:15:21
我编辑了消息@FreeAsInBeer希望你能帮助我 – Frenck 2012-03-16 19:28:59