Reputation: 1497
I have been trying to create a grid on the iPhone of 16x16 images.
- (void)viewDidLoad {
[super viewDidLoad];
int xLocation = 0;
for (int i=0; i <= 619; i++) {
if (((i % 30) == 0) && i != 0) { //if at end of column (30th row), moves x over 16 px to next column
xLocation += 16;
}
else {;}
CGRect imageRect = CGRectMake( xLocation, (16*i), 16, 16);
UIImageView *image = [[UIImageView alloc] initWithFrame:imageRect];
[image setImage:[UIImage imageNamed:@"Untitled-1.png"]];
[image setOpaque:YES];
NSLog(@"%d", xLocation);
[self.view addSubview:image];
[image release];
}
The problem is the int xLocation. For some reason, CGRectMake uses 0 in the x-coordinate slot instead of xLocation. I say "instead of" because the NSLog below it reveals that the xLocation has the values that I want it to, so the assignment of the values is working fine. What is going on here?
Upvotes: 1
Views: 630
Reputation: 5787
Casting xLocation as an int in your NSLog will certainly work, but you could also use:
NSLog(@"imageRect %@", NSStringFromCGRect(imageRect));
There are a whole series of NSStringFromXXX helper functions that come in handy from time to time.
Upvotes: 3
Reputation:
The xLocation is 0 for the first column and it is being increased for each column but the y coordinate is not being reset to 0 for each new column. It just keeps increasing based on i. So the columns from the second onward are just off screen at the right xLocation but a high y value.
Try changing the imageRect calculation to:
CGRect imageRect = CGRectMake( xLocation, (16*(i % 30)), 16, 16);
Upvotes: 2
Reputation: 18343
%d doesn't present float's properly. Use %f or convert xLocation to an int:
NSLog(@"%d", (int)xLocation);
You can also simplify your xLocation calculation readability by calculating it each time, something like
16 * (i / 30)
The overhead is minimal on modern processors.
Upvotes: 1