按下时,我在随机位置移动UIButton时出现问题。练习是制作一个应用程序,用于统计按钮上的按键。在每次点击时,按钮必须改变其在屏幕上的位置。这是我的代码:按下时更改UIButton的位置
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (IBAction)buttonPressed:(id)sender {
//[self tapCountMethod];
}
- (IBAction)button:(UIButton *)sender {
UIButton *button = (UIButton *)sender;
int xmin = ([button frame].size.width)/2;
int ymin = ([button frame].size.height)/2;
int x = xmin + arc4random_uniform(self.view.frame.size.width - button.frame.size.width);
int y = ymin + arc4random_uniform(self.view.frame.size.height - button.frame.size.height);
[button setCenter:CGPointMake(x, y)];
[button addTarget:self action: @selector(buttonPressed:) forControlEvents: UIControlEventTouchUpInside];
}
- (void) tapCounter {
tapCount ++;
labelCount.text = [NSString stringWithFormat:@"%ld times", (long)tapCount];
}
@end
因此,当我在buttonpressed中调用tapCount方法时,按钮停止移动。有人可以告诉我为什么会发生这种情况,以及我错了什么。你有什么建议请告诉我。我必须在哪里调用count方法?
@property(强,非原子)IBOutlet中的UIButton *按钮; (IBAction)按钮:(UIButton *)发送者{int xmin =([self.button frame] .size.width)/ 2; int ymin =([self.button frame] .size.height)/ 2; int x = xmin + arc4random_uniform(self.view.frame.size.width - self.button.frame.size.width); int y = ymin + arc4random_uniform(self.view.frame.size.height - self.button.frame.size.height); [self.button setCenter:CGPointMake(x,y)]; [self.button addTarget:self action:@selector(buttonPressed :) forControlEvents:UIControlEventTouchUpInside]; } 这不帮助我。仍然是一样的 – Newbie 2014-12-05 15:03:53
不清楚你如何从界面构建器接线,但你可能不应该在你的“按钮”方法中添加一个目标到按钮。为什么不只是在一种方法中执行两个任务(移动,计数),或者至少直接调用IBAction方法中的移动和计数方法? – 2014-12-05 15:32:47