我想要一个按钮随机出现,并有一个用户点击它。然而,如果他们没有在正确的时间内按下它,它就会消失,我想让它移动到不同的位置。然而,每当我不点击它时,它就会出现在屏幕上的同一位置。这是我的代码。
-(IBAction)randomRed:(id)sender
{
[self redDot];
CGRect senderFrame = [sender frame];
CGRect superBounds = [[sender superview ] bounds];
senderFrame.origin.x = (superBounds.size.width - senderFrame.size.width) * drand48();
senderFrame.origin.y = (superBounds.size.height - senderFrame.size.height) * drand48();
[sender setFrame:senderFrame];
counter = counter-1;
[self performSelector:@selector(showRedDot) withObject:nil afterDelay:1.0];
}
-(void)startRedDot
{
if (counter ==0)
redDot = [NSTimer scheduledTimerWithTimeInterval:4.0
target:self
selector:@selector(showRedDot)
userInfo:nil
repeats:YES];
}
-(void)showRedDot
{
{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:1.0];
[redButton setAlpha:1];
[UIView commitAnimations];
[self performSelector:@selector(redDot) withObject:nil afterDelay:1.0];
}
}
-(void)redDot
{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.5];
[redButton setAlpha:0];
[UIView commitAnimations];
}发布于 2014-07-26 00:15:17
drand48()是一个种子随机生成器,所以它只是伪随机的。在程序开始时,可以调用srand48(int),然后当需要一个随机数时,使用drand48()。在srand48(int)中使用的整数是随机数的“种子”;也就是说,每次使用该种子时,“随机”数的序列都是相同的。
你说,不是那么随机的吧?如果你想做更多的事情,可以试试arc4random()。为了方便起见,您可以使用(arc4random() % x)来获取0- (x-1)范围内的随机数。
希望这能有所帮助!
https://stackoverflow.com/questions/24948068
复制相似问题