2013-08-22 2 views
2

특정보기에서 임의의 위치에 단추를 만들려고합니다. 검색 및 일부 SO 항목을 읽었지만 내 문제에 대한 솔루션을 찾을 수 없습니다. 당신은 매개 변수로 플로트를 사용하여 계수를 계산하기 위해 노력하고 있기 때문에 아마 그 오류가 발생Arc4random 오류 : "이진 표현식에 잘못된 피연산자 ('float'및 'float')가 있습니다.

UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom]; 
CGRect buttonRect = button1.frame; 
buttonRect.size = CGSizeMake(100, 100); 
button1.frame = buttonRect; 

[self.arr addObject:button1]; 

int r = ([button1 frame].size.width)/2; 

int x = r + (arc4random() % (self.view.frame.size.width - button1.frame.size.width)); 
int y = r + (arc4random() % (self.view.frame.size.height - button1.frame.size.height)); 
//ERROR:Invalid operands to binary expression ('float' and 'float') 

[button1 setCenter:CGPointMake(x, y)]; 
+0

중복 가능성 [? 목표 -C/코코아 터치의 모듈로 연산을 만드는 방법 (http://stackoverflow.com/questions/1271102/how- : 여기

은 바람직한 방법 to-make-a-modulo-operation-in-objective-c-cocoa-touch) – kovpas

+0

'width'가'CGfloat'이므로 오류가 발생합니다. – Exploring

답변

9

mod (%)는 부동 소수점에서 작동하지 않습니다. 추가 참고로


int x = r + (arc4random() % (int)(self.view.frame.size.width - button1.frame.size.width)); 
int y = r + (arc4random() % (int)(self.view.frame.size.height - button1.frame.size.height)); 

, arc4random() % …not recommended입니다.

int x = r + arc4random_uniform(self.view.frame.size.width - button1.frame.size.width); 
int y = r + arc4random_uniform(self.view.frame.size.height - button1.frame.size.height); 
+0

빠른 응답을 보내 주셔서 감사합니다. – THO

3

시도 변경

int x = r + (arc4random() % (self.view.frame.size.width - button1.frame.size.width)); 
int y = r + (arc4random() % (self.view.frame.size.height - button1.frame.size.height)); 

int x = r + (arc4random() % ((int)(self.view.frame.size.width - button1.frame.size.width))); 
int y = r + (arc4random() % ((int)(self.view.frame.size.height - button1.frame.size.height))); 

에 : 여기

내 코드입니다

+0

괄호 밖에서'(int)'캐스팅을해야합니다. 그렇습니까? – bdesham

+0

당신은 나를 때렸어. –

+0

네 말이 맞아, 나는 대답을 – Daniel

관련 문제