我正在尝试在视图上随机分发大量标签。下面的代码有效,但显然分布不是很随机,因此我在这一行中替换
cat.frame = CGRectMake(self.view.frame.size.width - ( 50 * arc4random() % self.numOfCats), (50 * arc4random() % self.numOfCats), 100, 100);
尝试至少创建一些相似性的随机性,但是,屏幕上没有出现任何标签,也没有错误消息。你能解释一下原因吗?
加成 我不认为创建随机性的方法也很好(即不可能在0,0得到任何),奖金,你能改进创建随机性的方法吗?我必须确保没有任何标签也重叠......
for (int i = 1; i <= self.numOfCats; i++) {
Cat *cat = [self timer];
cat.frame = CGRectMake(self.view.frame.size.width - 500 , 100 * i, 100, 100);
[self.view addSubview:cat];
}
答案 0 :(得分:1)
这可以让您了解更好地处理标签随机位置的方法:
CGRect newFrame = cat.frame; //The original frame, whichever it was considering size
//Consider the width of the cat to avoid placing it outside of the screen
newFrame.origin.x = [self randomFloatBetweenLowerLimit:0
upperLimit:CGRectGetWidth(self.view.frame) - CGRectGetWidth(cat.frame)];
//Consider the width of the cat to avoid placing it outside of the screen
newFrame.origin.y = [self randomFloatBetweenLowerLimit:0
upperLimit:CGRectGetHeight(self.view.frame) - CGRectGetHeight(cat.frame)];
cat.frame = newFrame;
这是获取随机浮点数的方法,考虑模偏差:
- (CGFloat)randomFloatBetweenLowerLimit:(CGFloat)lowerLimit
upperLimit:(CGFloat)upperLimit
{
return arc4random_uniform(UINT32_MAX) / (CGFloat)UINT32_MAX * (upperLimit - lowerLimit) + lowerLimit;
}