How to Create Button in in multiple row and column in iOS? - ios

I am stuck in this position from last 3 days. I am unable to find out how to solve this. I have multiple data in a array. According to data I have to create a route in my Application. I am creating the button in a for loop. but its coming one row by row. But my requirement is like, in every row it should be a opposite direction.
This is my requirement.
This purple color is my buttons, and red colors are path.
int x_pos = 40;
int y_pos = 50;
for (int i = 0; i < 5 ; i ++)
{
UIButton *courseBtn = [UIButton buttonWithType:UIButtonTypeCustom];
courseBtn.frame = CGRectMake(x_pos, y_pos, 40, 40);
courseBtn.backgroundColor = [UIColor purpleColor];
[self.courseMapScroll addSubview:courseBtn];
courseBtn.layer.cornerRadius = courseBtn.frame.size.height/2;
courseBtn.layer.masksToBounds = YES;
NSLog(#"x_pos == %d",x_pos);
x_pos = x_pos + (SCREEN_WIDTH - 120);
if (x_pos > 320)
{
x_pos = 40;
y_pos = y_pos + 100;
}
[self.courseMapScroll setContentSize:CGSizeMake(SCREEN_WIDTH, y_pos + 70)];
}
My code is like this
Please anybody can help me. Please
Thanks alots

Here it is, exactly how you asked for it (with the green line that you requested in chat). Have fun tweaking the values :)
int numButtons = 6;
int yInterval = 100;
int leftX = 50;
int rightX = self.view.frame.size.width - leftX*2;
int lineWidth = 6;
int buttonRadius = 40;
int topMargin = 60;
for (float i = 1; i < numButtons+1 ; i++) {
float yPos = (ceil(i/2)-1)*yInterval+topMargin;
BOOL isRightDirection = (fmod(ceil(i/2),2) == 1);
BOOL isEven = (fmod(i,2) == 0);
BOOL isOnLeft = (isRightDirection != isEven);
float xPos = (isOnLeft) ? leftX : rightX;
if (i != numButtons) {
double nextUnlockedDecimal = (double)nextPercentUnlocked/100;
UIView *redLine = [[UIView alloc] initWithFrame:CGRectZero];
redLine.backgroundColor = [UIColor redColor];
UIView *greenLine = [[UIView alloc] initWithFrame:CGRectZero];
greenLine.backgroundColor = [UIColor greenColor];
if (isEven) {
//Vertical
int xToUse = (isRightDirection) ? rightX : leftX;
redLine.frame = CGRectMake(xToUse + buttonRadius/2 - lineWidth/2, yPos + buttonRadius/2, lineWidth, yInterval);
if (i == latestUnlocked) {
greenLine.frame = CGRectMake(xToUse + buttonRadius/2 - lineWidth/2, yPos + buttonRadius/2, lineWidth, nextUnlockedDecimal * yInterval);
} else if (i < latestUnlocked) {
greenLine.frame = redLine.frame;
}
} else {
//Horizontal
redLine.frame = CGRectMake(leftX + buttonRadius/2, yPos + buttonRadius/2 - lineWidth/2, rightX-leftX, lineWidth);
if (i == latestUnlocked) {
double greenLineX = (isRightDirection) ? leftX + buttonRadius/2 : rightX + buttonRadius/2 - nextUnlockedDecimal * (rightX-leftX);
greenLine.frame = CGRectMake(greenLineX, yPos + buttonRadius/2 - lineWidth/2, nextUnlockedDecimal * (rightX-leftX), lineWidth);
} else if (i < latestUnlocked) {
greenLine.frame = redLine.frame;
}
}
greenLine.layer.cornerRadius = 2.5;
[self.view addSubview:redLine];
[self.view addSubview:greenLine];
}
UIButton *courseBtn = [UIButton buttonWithType:UIButtonTypeCustom];
courseBtn.backgroundColor = [UIColor purpleColor];
courseBtn.layer.cornerRadius = buttonRadius/2;
courseBtn.layer.masksToBounds = YES;
courseBtn.frame = CGRectMake(xPos, yPos, 40, 40);
NSString *numStr = [NSString stringWithFormat:#"%i",(int)i];
[courseBtn setTitle:numStr forState:UIControlStateNormal];
[self.courseMapScroll setContentSize:CGSizeMake(SCREEN_WIDTH, yPos + 70)];
[self.courseMapScroll addSubview:courseBtn];
}

I don't know why I really did that... This should work, I haven't tested it though... I would recommend you to use a global mutable array (courseButtons) to store the buttons so you can check on the target their index against the array and know which one was clicked.
CGFloat buttonHorizontalMargin=40;
CGFloat buttonVerticalMargin=50;
CGFloat buttonSize=40;
CGFloat x_pos = buttonHorizontalMargin;
CGFloat y_pos = buttonVerticalMargin;
[self.courseMapScroll setContentSize:CGSizeMake(self.courseMapScroll.bounds.size.width, y_pos + buttonSize+buttonVerticalMargin*0.5)];
for (NSInteger i = 0; i < [_buttonPoints count] ; i ++)
{
UIButton *courseBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[courseBtn setTitle:[NSString stringWithFormat:#"%ld",(long)i] forState:UIControlStateNormal];
[courseBtn setTranslatesAutoresizingMaskIntoConstraints:YES];
[courseBtn setAutoresizesSubviews:(((i+1)%2==0&&(i+1)%4!=0)||(i+1)%3==0)?UIViewAutoresizingFlexibleLeftMargin:UIViewAutoresizingRightMargin];
[courseBtn addTarget:self action:#selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
courseBtn.frame = CGRectMake(x_pos, y_pos, buttonSize, buttonSize);
courseBtn.backgroundColor = [UIColor purpleColor];
[self.courseButtons addObject:courseBtn];
[self.courseMapScroll addSubview:courseBtn];
courseBtn.layer.cornerRadius = courseBtn.frame.size.height*0.5;
courseBtn.layer.masksToBounds = YES;
NSLog(#"x_pos == %d",x_pos);
if((i+1)%4){
x_pos = buttonHorizontalMargin;
}else if((i+1)%3||(i+1)%2){
x_pos = self.courseMapScroll.bounds.size.width-buttonHorizontalMargin-buttonSize;
}else{
x_pos = buttonHorizontalMargin;
}
if (i>0 && i%2==0){
y_pos = y_pos + buttonSize+buttonVerticalMargin;
[self.courseMapScroll setContentSize:CGSizeMake(self.courseMapScroll.bounds.size.width, y_pos + buttonSize+buttonVerticalMargin*0.5)];
}
}

Related

Change color of chess field after rotate

I newbie in Obj-C.
I have the following chess field:
for (int row = 0; row < 8; row++) {
for (int column = 0; column < 8; column++) {
CGRect square = {horizontalOffSet + (column * squareSize),
verticalOffSet + (row * squareSize),
squareSize, squareSize};
UIView *rect = [[UIView alloc] initWithFrame:square];
rect.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
horizontalOffSet = horizontalOffSet + squareSize;
if ((row + column) % 2 == 0) {
//verticalOffSet = verticalOffSet + squareSize;
horizontalOffSet = 0;
rect.backgroundColor = [UIColor whiteColor];
[anotherRect addSubview:rect];
} else {
//verticalOffSet = verticalOffSet + squareSize;
horizontalOffSet = 0;
rect.backgroundColor = [UIColor blackColor];
[anotherRect addSubview:rect];
}
}
}
My task to change colours of the field when it rotates, for example, fill it with cyan and purple colour when rotating on left. Not clearly understand how to do it.
#somerk check my updated code:
1) I have give identifier(tag) to identified chess view and which has white and which has black color. you can do it without identifier but in case of multiple subviews identifier is better way to get.
int horizontalOffSet = 2;
int squareSize = 40;
int verticalOffSet = 2;
for (int row = 0; row < 8; row++) {
for (int column = 0; column < 8; column++) {
CGRect square = {horizontalOffSet + (column * squareSize),
verticalOffSet + (row * squareSize),
squareSize, squareSize};
UIView *rect = [[UIView alloc] initWithFrame:square];
rect.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
horizontalOffSet = horizontalOffSet + squareSize;
if ((row + column) % 2 == 0) {
//verticalOffSet = verticalOffSet + squareSize;
horizontalOffSet = 0;
rect.tag = 101;
rect.backgroundColor = [UIColor whiteColor];
[self.view addSubview:rect];
} else {
//verticalOffSet = verticalOffSet + squareSize;
rect.tag = 102;
horizontalOffSet = 0;
rect.backgroundColor = [UIColor blackColor];
[self.view addSubview:rect];
}
}
2) I have performed color change event on UIButton click so you have to use that code after rotation event.
-(IBAction)changeColor:(UIButton *)btn{
for(UIView *rectViews in self.view.subviews){
UIColor *clrblck = [UIColor blackColor];
if(rectViews.backgroundColor == clrblck && rectViews.tag == 102){
rectViews.backgroundColor = [UIColor cyanColor];
}else if(rectViews.backgroundColor == clrblck && rectViews.tag == 101){
rectViews.backgroundColor = [UIColor purpleColor];
}else{
// you will get other views here..
}
}
}
I have get all subviews and check backgroundColor and tag and change its backgroundColor.
Note: change view'name according your view's name in loop and where you add rect as subviews in your anotherRect.
Free to ask me if you have any question. Happy Coding :)
Find another possible solution to change colors:
-(void) viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
[super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
CGFloat rndmColor1 = (float)(arc4random() % 256) / 255;
CGFloat rndmColor2 = (float)(arc4random() % 256) / 255;
for(UIView *rect in self.chessField.subviews){
if (rect.tag == 102) {
rect.backgroundColor = [UIColor colorWithHue:rndmColor1 saturation:1 brightness:1 alpha:1];
} else if (rect.tag == 101) {
rect.backgroundColor = [UIColor colorWithHue:rndmColor2 saturation:1 brightness:1 alpha:1];
}
}
}

Draw grid of circles

What would be the best way on iOS to achieve drawing a grid of circles with fixed columns and rows ?. I would want to identify each circle when the user taps on it.
I tried using collection views but it seems CoreGraphics is meant for tasks like these.
You can create buttons dynamically as follows :
- (void)drawSheet
{
int numberOfRow=5;
int numberOfColumn=4;
float x = 1,
y = 20,
padding = 5,
width = (self.view.frame.size.width-(padding*(numberOfColumn-1)))/numberOfColumn,
height = (self.view.frame.size.height-(padding*(numberOfRow-1)))/numberOfRow;
int counter = 0;
for (int i=0; i<numberOfRow; i++) {
for (int j=0; j<numberOfColumn; j++) {
UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(x, y, 74, 74)];
btn.layer.cornerRadius = btn.frame.size.width/2;
btn.layer.borderColor = [UIColor grayColor].CGColor;
btn.layer.borderWidth = 2.0;
[btn addTarget:self action:#selector(buttonPress:) forControlEvents:UIControlEventTouchUpInside];
btn.clipsToBounds = YES;
btn.tag = counter;
[self.view addSubview:btn];
x = x + width + padding;
counter = counter + 1;
}
x = 0;
y = y + height + padding;
}
}
When you tap on it, you will get tag of it :
- (IBAction)buttonPress:(UIButton *)sender{
NSLog(#"%ld",sender.tag);
}
hi Please check the below code. i have added 3 circles in a row, you could use more if you want.
- (void)viewDidLoad {
[super viewDidLoad];
UIView *circleView;
int x = 10;
int y = 20;
static int tagNum = 0;
for (int row=0; row < 5;) {
for (int cirNum =0 ; cirNum <3;) {
circleView = [[UIView alloc] initWithFrame:CGRectMake(x,y,100,100)];
circleView.alpha = 0.5;
circleView.layer.cornerRadius = 50;
circleView.backgroundColor = [UIColor blueColor];
circleView.tag = tagNum;
NSLog(#"tagNum is %d", tagNum);
[self.view addSubview:circleView];
cirNum ++;
x = x + 100;
tagNum ++;
//y = y + 20;
}
row++;
y = y + 100;
x = 10;
}
// Do any additional setup after loading the view, typically from a nib.
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
CGPoint location = [[touches anyObject] locationInView:self.view];
CGRect fingerRect = CGRectMake(location.x-5, location.y-5, 10, 10);
for(UIView *view in self.view.subviews){
CGRect subviewFrame = view.frame;
if(CGRectIntersectsRect(fingerRect, subviewFrame)){
//we found the finally touched view
//NSLog(#"Yeah !, i found it %#",view);
NSLog(#"view tag touched is %ld",view.tag);
}
}
}
output would look like this

Certain placement of UIButtons created in for loop

I want to create UIButtons and have them separated inside a UIScrollView with pages such as:
The buttons will go from left to right then down in rows until it gets to bottom of view. It will then go to next page of the UIScrollView and continue on.
Here's my code so far:
for(NSString *num in nums) {
UIButton *test = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[test addTarget:self action:#selector(numPressed:) forControlEvents:UIControlEventTouchUpInside];
test.frame = CGRectMake(0, 0, 70, 70);
[self.view addSubview:test];
}
Some code like this:
int xOff = 10;
int yOff = 50;
int btnGap = 20;
int page = 0;
for (NSString *num in nums) {
xOff += page * _scrollView.width;
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
UIButton *test = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[test addTarget:self action:#selector(numPressed:) forControlEvents:UIControlEventTouchUpInside];
test.frame = CGRectMake(xOff+col*(70+btnGap) , yOff+row*(70+btnGap), 70, 70);
test.backgroundColor = [UIColor redColor];
[test setTitle:num forState:UIControlStateNormal];
[_scrollView addSubview:test];
}
}
page++;
}
You need to change the coordinates when invokint CGRectMake:
NSInteger i, x, y;
for(NSString *num in nums) {
...
i = i%3;
if (i==0)
{
x = 0;
y += 70;
}
x += 80;
test.frame = CGRectMake(x, y, 70, 70);
...
}
This should give you an idea on how to proceed. Also, don't forget to place the title to each button.
If you're creating and setting UIButton objects by frame then I, personally, would do it this way (surely it can be improved / optimized)
Note: This does not incorporate any page logic so you'll need to adapt it yourself.
-(void)createButtonGrid
{
int i_btnWidth = 70;
int i_btnHeight = 70;
int i_btnX = 0;
int i_btnY = -70; //offset (for first iteration in for loop) [1]
int i_btnPadding = 20;
//number of columns
int i_screenDivisions = 3;
//width of every column
int i_screenDivisionWidth = self.view.frame.size.width / i_screenDivisions;
int i_count = 40; //or, maybe, nums.count as per your logic
for (int i = 0; i < i_count; i++) {
//which column a button goes in
int i_index = (i+i_screenDivisions)%i_screenDivisions;
//increase Y position when new row begins
if (i_index == 0) { //[1]
i_btnY += i_btnHeight + i_btnPadding;
}
//calculate X position (which will be placed at the centre of every column)
i_btnX = (i_index*i_screenDivisionWidth) + (i_screenDivisionWidth/2) - (i_btnWidth/2);
//----Button creation logic----
UIButton *btnTemp = [UIButton buttonWithType:UIButtonTypeCustom];
[btnTemp setFrame:CGRectMake(i_btnX, i_btnY, i_btnWidth, i_btnHeight)];
NSString *strTitle = [NSString stringWithFormat:#"%d",i];
//or, maybe, as per your logic
//NSString *strTitle = nums[i];
[btnTemp setTitle:strTitle forState:UIControlStateNormal];
[btnTemp.titleLabel setTextColor:[UIColor yellowColor]];
//[btnTemp addTarget:self action:nil forControlEvents:UIControlEventTouchUpInside];
[btnTemp setTag:i]; //might need it later
[btnTemp setBackgroundColor:[UIColor colorWithRed:(float)(arc4random()%255)/255
green:(float)(arc4random()%255)/255
blue:(float)(arc4random()%255)/255
alpha:1.0f]];
[scrollView addSubview:btnTemp];
}
[scrollView setContentSize:CGSizeMake(self.view.frame.size.width, i_btnY + i_btnHeight)];
}

Custom UIPageControl dots are misplaced on load

I have a weird behavior with custom UIPageControl.
I subclassed it and in setCurrentPage method I draw custom dots.
In iOS 6 on load they just miss.
In iOS 7 the dots are misplaced.
In both iOS's dots are being positioned correctly only after I change the slide.
I tried the following methods without success:
[customPageControl updateCurrentPageDisplay];
[customPageControl updateConstraints];
[customPageControl sizeToFit];
[customPageControl.currentPage = 1];
The code:
#implementation ProfilePagesPageControl
#synthesize originalSubviews;
#synthesize dotsHeight;
- (void)setCurrentPage:(NSInteger)page
{
[super setCurrentPage:page];
[self updateDots];
}
- (void)updateDots
{
for (int i = 0; i < self.subviews.count; i++)
{
UIView* dotView = [self.subviews objectAtIndex:i];
for (int j = dotView.subviews.count - 1; j >= 0; j--)
{
UIView *view = [dotView.subviews objectAtIndex:j];
[view removeFromSuperview];
}
int widthForDots = [Utils getDeviceBounds].width - Constraints.Gap * 3;
int effectiveWidth = widthForDots / self.subviews.count - Constraints.Gap;
int effectiveGap = (widthForDots - (effectiveWidth * self.subviews.count) + Constraints.Gap * 3) / self.subviews.count;
int effectiveHeight = dotsHeight;
if (i == self.currentPage)
effectiveHeight = effectiveHeight + 3;
else
effectiveHeight = effectiveHeight - 3;
CGRect dotViewFrame = dotView.frame;
dotViewFrame.origin.x = effectiveWidth * i + Constraints.Gap + effectiveGap * i;
dotViewFrame.origin.y = self.frame.size.height / 2 - effectiveHeight / 2;
dotViewFrame.size.width = effectiveWidth;
dotViewFrame.size.height = effectiveHeight;
dotView.frame = dotViewFrame;
UIView *dotSubView = [[UIView alloc] initWithFrame:CGRectMake(0,
0,
dotView.frame.size.width,
dotView.frame.size.height)];
if (i == self.currentPage)
dotSubView.backgroundColor = [UIColor blackColor];
else
dotSubView.backgroundColor = [UIColor grayColor];
[UIUtils roundCorner:(UIRectCornerTopLeft | UIRectCornerTopRight | UIRectCornerBottomLeft | UIRectCornerBottomRight) forView:dotSubView];
ProfileSlideView *slideView = [self.originalSubviews objectAtIndex:i];
RevUILabel *label = [[RevUILabel alloc] initWithSize:13];
label.text = slideView.name;
label.frame = CGRectMake(dotSubView.frame.size.width / 2 - label.frame.size.width / 2,
dotSubView.frame.size.height / 2 - label.frame.size.height / 2,
label.frame.size.width,
label.frame.size.height);
[dotSubView addSubview:label];
[dotView addSubview:dotSubView];
}
}
#end
The iOS7 look:
The iOS6 look:
:
After slide look:
Make sure you call updateDots somewhere else (such as viewDidLoad, or viewWillAppear) so they can be set up before you switch any pages. If you only call updateDots in setCurrentPage it will only be called once you switch the page the first time.

How to add UIButtons programatically using for loop in iOS?

I want to create 15 UIButtons progaramatically using for loop. I want to arrange buttons like matrix with rows and colums, say 3 rows and 5 columns. The buttons height is 50 and width is 80. I can set y,width,height coordinates. But I face problem only with x coordinate. Tell me the logic for setting x coordinate.
Thanks in advance.
float x = 10;
float y = 10;
float width = 50;
float height = 50;
for(int i =0;i<15;i++)
{
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btn setFrame:CGRectMake(x, y, width, height)];
[btn setTitle:[NSString stringWithFormat:#"B%d",i+1] forState:UIControlStateNormal];
[self.view addSubview:btn];
x = x + width + 20;
if((i+1)%3==0)
{
x = 10;
y = y + height + 20;
}
}
Just replace x and y and also set height and width in above code.
int row = 0;
int column = 0;
for (int i = 0; i < 15; i++)
{
if((row%3 == 0) && (row > 0))
{
row = 0;
column++;
}
else{
row++;
}
CGRect btnFrame = CGRectMake(row*80+10, column*50+10, 80, 50);//your button frame
UIButton *btnTemp = [UIButton buttonWithType:UIButtonTypeCustom];
[btnTemp setFrame:btnFrame];
[self.view addSubView:btnTemp];
}
Here you go:
CGFloat marginX = 10.f;
CGFloat marginY = 5.f;
CGRect buttonFrame = CGRectMake(0., 0., 80., 50.f);
for(NSUInteger row = 0; row < 5; row++) {
for(NSUInteger column = 0; column < 3; column++) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = buttonFrame;
//... more button settings
[self.view addSubview:button];
buttonFrame.origin.x += marginX;
}
buttonFrame.origin.x = 0.;
buttonFrame.origin.y += marginY;
}

Resources