How to generate a line of images programmatically on Xcode - ios

I am trying to make an iOS game and it requires for the players to catch as many coins as it can. I know to show the coins programmatically, but how do I make a line of coins with ease. Similarly like the game line runner where the runner has to catch the coins or jetpack joyride?
I'm thinking of something like
The game is landscape
randomPlace = arc3random()%315;
coinImage.center = CGPointMake(coinImage.center.x - 1, randomPlace);
coinImage1.center = CGPointMake(coinImage1.center.x - 1, randomPlace);
I don't even know if I'm on the right track but can anyone help me? thank you!

You could use something like this to create 5 images in a horizontal line:
//Generate your variables
float width = 15, height = 15;
float originX = 20, originY = 50, spacing = 5;
//Create 5 image views
for (int i = 0; i < 5; i++) {
UIImageView *imgV = [[UIImageView alloc] initWithFrame:CGRectMake(originX + ((spacing + width) * i), originY, width, height)];
[imgV setImage:[UIImage imageNamed:#"YourImage.png"]];
[self.view addSubview:imgV];
}
Which will produce something like this:

Related

XCODE Obj-C add UiimageView programatically in a for

So i need to add programatically 3 images using a for loop this is my code , it's not correct, i just tryed.
for(int i = 1; i < 4; i++){
UIImageView *[i] = [[UIImageView alloc] initWithFrame:CGRectMake([i]*50, 50, 250, 250)];
[self.view addSubview:[i]];
}
where [i]; will be 1 , 2 and 3 any help would be appreciated. Thanks
You syntax is wrong. This is more what you need.
for (int i=0;i<3;i++){
UIImageView *image=[[UIImageView alloc] initWithFrame:CGRectMake(i*50, 50, 250, 250)];
[self.view addSubView:image];
}
However, this is not much use to you as your images are not referenced from anywhere so you can not populate or adjust them easily.
Change the variable name from [i] to some name like imageToAdd.
CGFloat xMarging = 0;
CGFloat imageOriginX = 0;
CGFloat imageOriginY = 0;
CGFloat imageWidth = 250;
CGFloat imageHeight = 250;
NSInteger numerOfImages = 3;
for (NSInteger i = 0; i < numerOfImages; i++){
[self.view addSubview:[[UIImageView alloc] initWithFrame:CGRectMake(xMarging + i * imageWidth,
imageOriginY,
imageWidth,
imgageHeight)]];
}
assuming you want them side by side as in [][][]

Add buttons to UIView

I would like to add buttons to an UIView. The number of buttons varies from view to view.
I want to achieve the following:
I tried to add the Buttons (in a foreach construct) like this:
UIButton *but=[UIButton buttonWithType:UIButtonTypeRoundedRect];
but.frame= CGRectMake(200, 15, 15, 15);
[but setTitle:#"Ok" forState:UIControlStateNormal];
[but addTarget:self action:#selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:but];
But I don't know how to calculate the CGRectMake when it comes to an new line. How can I check the end of the line (UIView)? Or is it kinda stupid to add Buttons like this?
Thanks
Florian
You need to add calculate buttons size after you set the title. Then keep track of the current X and Y of the previous buttons and figure out if the newly created button can fit on the current "line". Otherwise go to the next one.
I suggest you to look at existing components and see how they do it, below are a couple links.
https://github.com/domness/DWTagList
https://github.com/andreamazz/AMTagListView
With the following code , you can place multiple buttons in one row as long as their total width and the gap is smaller then the view's width.
UIView *view = nil;
NSArray *allBtns = nil;
float viewWidth;
float currentY = 0;
float currentX = 0;
float btnGapWidth = 10.0;
float btnGapHeight = 2.0;
for (UIButton *btn in allBtns) {
CGRect rc = btn.frame;
BOOL shouldAddToNewLine = viewWidth - currentX - btnGapWidth < rc.size.width ? YES : NO;
if (shouldAddToNewLine) {
rc.origin = CGPointMake(0, currentY + rc.size.height + btnGapHeight);
currentX = 0;
currentY += rc.size.height + btnGapHeight;
} else {
//another row
rc.origin = CGPointMake(currentX + rc.size.width + btnGapWidth, currentY);
currentX += rc.size.width + btnGapWidth;
}
btn.frame = rc;
[view addSubview:btn];
}

Spawn UIImageView So That It Does Not Intersect With Existing UIImageViews

Basically, I have an app where a user dodges bombs and collects coins. When a user collects a coin, another coin is spawned. I want each coin to not spawn on a bomb. (By the way these are all uiimageviews). In the code below, I have an array of my bombs called bombArray and the UIImageview called "one" is the coin UIImageView. I know the code below doesn't work, but what other method(s) could I use? Thanks, and here is the code:
UIImageView *one = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#"goldCoin.png"]];
CGRect rectOne = CGRectMake(arc4random() % (900), arc4random() % (700), 40, 40);
[one setFrame:rectOne];
[self.view addSubview:one];
for (UIImageView* two in bombArray)
{
while (CGRectIntersectsRect(two.frame, one.frame))
{
one.center=CGPointMake(arc4random() % (900), arc4random() % (700));
}
}
*Note: I completely understand why the code above does not work, but I cannot find another solution to my problem.
First of all to make such a thing I'd use the new SpriteKit that gives you physics (and thus collision detection) out of the box.
But if you want to do this with standard UIViews what you can do for being absolutely sure that images don't collide between them is to divide the container in a grid and then loop through each cell of your grid and "flip a coin" to randomly put a coin or not in that cell. Then if you want to fill more space instead of dividing for rectangular cells you can divide for hexagonal cells, in this way you will cover more space.
So a fast and absolutely not too much checked version could be something like this:
int x = 0;
int y = 0;
int side = 40;
int it = 0;
do {
do {
CGRect imageFrame = CGRectMake(x, y, side, side);
UIImageView* imageView = [[UIImageView alloc] initWithFrame:imageFrame];
imageView.layer.borderColor = [UIColor blackColor].CGColor;
imageView.layer.borderWidth = 1.0;
imageView.layer.cornerRadius = side / 2;
imageView.layer.masksToBounds = YES;
[self.containerView addSubview:imageView];
BOOL flip = arc4random() & 0x1;
if (flip) {
[imageView setImage:[UIImage imageNamed:#"coin_image"]];
}
} while ((x+=side) < (self.containerView.frame.size.width - side / 2));
it++;
if (it % 2 != 0) {
x = side / 2;
} else {
x = 0;
}
} while ((y+=(side * 0.85)) < (self.containerView.frame.size.height - side) );
Mind that this is NOT efficient, it is executed in the main thread and doesn't take in account possible (actually probable) memory constraints.

Dyamic frame calculation for UIImages in UITableViewCell

I am putting few icons on UITableViewCell. The number of icons can vary from 1 to 6. Icons should not have fixed X position and instead they should be dynamically placed considering the cell space. So if there are 3 icons they should look placed centric to the cell. Also, the icon spacing should also vary. For instance when it is 6 icons all of them will be placed with less margins in between and when there are 3 then margin will be more and so will be the X position.
Please suggest some quick way to calculate this frame. I am running the app both on iOS 6 and iOS 7.
This is what I have tried by far but this does not seems to work well with icon count variation. Also, in between space is not dynamic with this.
int maxIconTypes = 6;
CGFloat innerPadding = ([self isIOS7]) ? 15.0f : 9.0f;
CGRect adjustedBoundsIOS6 = [self bounds];
CGFloat adjustedWidth = ([self isIOS7]) ? self.bounds.size.width : adjustedBoundsIOS6.size.width;
CGFloat xOrigin = innerPadding;
CGFloat iconViewSize = 25.0f;
CGFloat ySpacer = (self.bounds.size.height - iconSize) / 2;
CGFloat xSpacer = ((adjustedWidth - (innerPadding * 2)) - (maxRequestTypes * iconViewSize)) / (maxIconTypes - 1);
for (NSString *icon in iconList) {
UIImageView *anIconView = [[UIImageView alloc] initWithImage:[UIImage icon]];
if (anIconView.image) {
anIconView.frame = CGRectMake(xOrigin + originPadding, ySpacer, anIconView.image.size.width, anIconView.image.size.height);
[self.contentView addSubview:anIconView];
xOrigin += anIconView.frame.size.width + xSpacer;
}
}
However many items you have, the number of spaces is the same if you want equal spacing with half spacing at the start and end:
half width full width half
half width full width full width half
So, you just need to know the full width available and the combined width of the items. A simple multiply (to get the combined width of the items) and subtract (from the full width available) gives you the remaining width for the 'spacers'. Divide by the number of items to get the xSpacer, set the initial xOrigin to xSpacer * 0.5
Here is an example of what Wain is explaining:
//Im doing this in a UIView rather than in a UITableViewCell but idea is the same
int cellWidth = CGRectGetWidth(self.view.bounds);
//num of icons
int iconCount = 6;
//size of icon
int iconSize = 25;
//The max padding we can have
float maxPadding = (cellWidth - (iconSize * iconCount)) / iconCount;
//Our offset
float xOrigin = maxPadding / 2;
//Loooop
for (int i = 0; i < iconCount; i++) {
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(xOrigin, self.view.center.y, iconSize, iconSize)];
xOrigin += (iconSize + maxPadding);
label.backgroundColor = [UIColor blueColor];
[self.view addSubview:label];
}

How to make grid of elements in iOS?

So I'm about to make an app for iOS in xCode (go figure), and I am curious as to what people would suggest to do here.
My goal is to create a grid of buttons mxn in dimensions. I recently made a tic tac toe game variation where I had an overall 9x9 grid of buttons. It was very tedious work to create each button.
Would there be an easier way to create all these buttons through code?
Use a for loop to create the buttons. May be something of the following sorts to create a buttons for 3X3 grid
CGFloat xAxis,yAxis,bWidth,bHeight;
xAxis = 0.0;
yAxis = 0.0;
bWidth = 150.0;
bHeight = 44.0;
int numberOfRows = 3;
int numberOfColumns = 3;
int number = 1;
for(int i=0;i<numberOfRows;i++)
{
for(int j=0;j<numberOfColumns;j++)
{
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(xAxis, yAxis, bWidth, bHeight)];
button.titleLabel.text = [NSString stringWithFormat:#"%#",number];
number++;
[self.view addSubview:button];
xAxis = xAxis + bWidth + 5.0;
}
xAxis = 0;
yAxis = yAxis + bHeight + 5.0;
}
IBOutletCollections are a good candidate here, if you have a reasonable number of buttons. You can then loop through all of them to apply the same properties.

Resources