我在按下时随机移动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
因此,当我按下按钮时调用tapCount方法时,按钮停止移动。有人能告诉我为什么会这样,我错了。你有什么建议请告诉我。我必须在哪里调用计数方法?
答案 0 :(得分:0)
因此,经过多次尝试和研究,我找到了解决方案。这是我的最后一个代码。
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.button.imageView.animationImages =
[NSArray arrayWithObjects:[UIImage imageNamed:@"image1.png"],
[UIImage imageNamed:@"image2.png"],
nil];
self.button.imageView.animationDuration = 0.7; //whatever you want (in seconds)
[self.button.imageView startAnimating];
self.labelCount.textColor = [UIColor colorWithRed:64./255. green:64./255. blue:64./255. alpha:1.];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
}
- (IBAction)buttonPressed:(id)sender {
NSInteger counter = self.tapCount;
if (counter > 0 )
[self.labelCount setText:[NSString stringWithFormat:@"%ld",((long)counter + 1)]];
self.tapCount ++;
NSLog(@"%ld",(long)self.tapCount);
}
- (IBAction)button:(UIButton *)sender {
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];
[self.labelCount setText:[NSString stringWithFormat:@"1"]];
}
- (BOOL)prefersStatusBarHidden {
return YES;
}
@end
谢谢大家