Identifying the Position of a UIButton - iphone

I've created 5 buttons dynamically, as follows:
float xpos=0,ypos=0;
for (int i = 0; i < 5; i++)
{
but = [UIButton buttonWithType:UIButtonTypeCustom];
[but setTag:i];
[but setImage:[UIImage imageNamed:#"btfrnt.png"] forState:UIControlStateNormal];
[but setFrame:CGRectMake(xpos, ypos, 40, 40)];
xpos+=80;
[but addTarget:self action:#selector(checkboxButton:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:but];
}
In Click event of any of the button, I want to find the position of the button which I have clicked....
-(void)checkboxButton:(UIButton*)sender
{
NSLog(#"%d",xpos);
}
But, it displays only the xpos of the last button...Is there any way to identify it by means of its tag?

try this :
-(void)checkboxButton:(UIButton*)sender
{
NSLog(#"%f %f",sender.frame.origin.x,sender.frame.origin.y);
}

I take it xPos is a global variable - of course it contains the value of the last button, that's the value it was set to last.
For the button position you don't need to store anything in a global variable - just get it from the sender object that is delivered to you in the click event handler - it is a UIButton pointer, and the UIButton object has a frame structure with origin.x and origin.y, as well as a size.width and size.height, by the way.

You may try this...
-(void)checkboxButton:(UIButton*)sender {
UIButton *button = (UIButton *)sender;
CGRect rect = button.frame; //You may use sender.frame directly
NSLog(#"X: %d", rect.origin.x);
NSLog(#"Y: %d", rect.origin.y);
NSLog(#"Width: %f", rect.size.width);
NSLog(#"Height: %f", rect.size.height);
}

Related

Postioning UIImageSubview at center in UIScrollview

How to position the UIImageSubview at center in UIScrollview , I am Loading images dynalically in the uiscrollview so when i select any image in the Uiscrollview that Image should display at the center of screen in uiscrollview.
My Image Width is 65 and Screen width is 320 , I am facing problem setting the position of choosen image at the center of screen,
[scrollView1 setContentOffset:CGPointMake(130, 0) animated:YES];
scrollview just scroll to the 130 position. I don't want like this , I want the subview should be displayed at the center.
Please see the screenshot and tell me how to solve this problem.
How about
(pseudocode)
contentOffset.x = image.center.x - (screenwidth/2)
(expanded...)
UIImageView* imageView = //imageview that was selected
CGFloat screenWidth = 320;
CGPoint offset = scrollView1.contentOffset;
offset.x = imageView.center.x - screenWidth/2;
[scrollView1 setContentOffset:offset animated:YES];
I assume you already worked out how to get a pointer to the selected image...
(expanded further...)
Here is a fully-worked out version of the same, using buttons instead of images for ease of selection... try it (just copy into a new single-view project's viewContoller]), you will see that it works. If you are still having problems I expect it is the way you are identifying your image as the selected image for centering. You would need to update your question showing your code...
- (void)viewDidLoad
{
[super viewDidLoad];
CGRect frame = self.view.bounds;
frame.size.height = frame.size.height/2;
self.scrollView = [[UIScrollView alloc] initWithFrame:frame];
[self.view addSubview:self.scrollView];
[self.scrollView setContentSize:CGSizeMake(2000,self.scrollView.bounds.size.height)];
[self.scrollView setDelegate:self];
for (int i = 1; i < 20; i++) {
UIButton* button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
NSString* title = [NSString stringWithFormat:#"button %d",i];
[button setTitle:title forState:UIControlStateNormal];
button.bounds = CGRectMake(0,0,80,60);
button.center = CGPointMake(i*100+50,self.scrollView.bounds.size.height/2);
[button addTarget:self
action:#selector(buttonPressed:)
forControlEvents:UIControlEventTouchUpInside];
[self.scrollView addSubview:button];
}
}
- (void)buttonPressed:(UIButton*)sender
{
CGFloat x = sender.center.x - self.scrollView.bounds.size.width/2.0f;
[self.scrollView setContentOffset:CGPointMake(x,0) animated:YES];
}

A problem occurs when trying to change a button's frame in an animation block.

I created a button, with a custom image and displayed it in a frame.
Now I'm trying to change the button's frame, inside an animation block.
Unfortunately, it doesn't seem to work - the frame doesn't change as expected.
I have written the following code:
UIButton *movingButton = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
UIImage *image = [UIImage imageNamed:#"A_normal_image.png"];
[movingButton setImage:image forState:UIControlStateNormal];
movingButton.frame = CGRectMake(160, 240, 0, 0);
[movingButton addTarget:self action:#selector(moveButton:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:movingButton];
CGRect newFrame CGRectMake(20, 120, 44, 88);
[UIView animateWithDuration:0.5 animations:^{ movingButton.frame = newFrame; }];
[movingButton release];
Am I missing something? How should I do that then?
Thanks in advance,
Sagiftw
You should use floats instead of ints:
movingButton.frame = CGRectMake(160, 240, 0, 0);
to:
movingButton.frame = CGRectMake(160.0f, 240.0f, 0.0f, 0.0f);

Objective-c: Multiplying an object

This is a beginner's question about the fundamentals of objective programming (at least I think so..):
I have an UIView and would like to add several buttons to this UIView programatically. How many buttons there are depends on the user input.
Every button has four characteristics:
Its number (e.g. button number one, two, three etc.)
Its title (e.g. click this, click here, click me etc.)
Its position and size (i.e. a CGRect - size stays the same, only y-position needs to change)
Its colour (e.g. red, green, blue etc.)
Now I thought I can create a button by creating a method, but I am not entirely sure if this is a very sound method. I have the feeling that I should have created an object. Any help of how I should go about this would be very much appreciated. Here is my attempt - which is full of mistakes (for instance, I wasn't sure of how to create button1, button2 etc. -- hence the button[bNumber] thing):
-(void) createIndexButtonWithNumber:(NSString *)bNumber withTitle:(NSString *)bTitle atPosition:(NSInteger *)bPosition withColour:(NSInteger *)bColour {
CGRect buttonFrame = CGRectMake(0,bPosition,25,25);
UIButton* button[bNumber] = [[[UIButton alloc] initWithFrame:buttonFrame] autorelease];
UIButton.text = bTitle;
if (bColour == 1) {UIButton.color = [UIColor colorWithRed:0.751 green:0.742 blue:0.715 alpha:1.000];};
[indexView addSubview:button[bNumber]];
// to do: if button[bNumber] pressed {do something};
}
Then, I would like to 'multiply' the object three times by calling:
for (temp = 0; temp < 2; temp++) {
[self createIndexButtonWithNumber:temp withTitle:[#"Test%i", temp] atPosition:10 withColour:1];}
I'm sure this is all a bit problematic, wrong and clumsy, so I'd be very grateful for any suggestions of how to tackle this.
Here's a simple example that I wrote that creates 5 buttons vertically in a row. The only thing extra in there is the tag, which is used to later reference the button if you need to.
I would suggest reading some more object orientated program examples as well.
float buttonPadding = 20;
float buttonWidth = 80;
float buttonHeight = 40;
for (int k=0;k<5;k++)
{
UIButton* btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.tag = 1000 + k;
btn.frame = CGRectMake(0, k*(buttonPadding+buttonHeight), buttonWidth, buttonHeight);
[btn setTitle:[NSString stringWithFormat:#"Button %i", k+1] forState:UIControlStateNormal];
[self.view addSubview:btn];
}
I'd like to reference to UIButton Class Reference
You should create buttons only with buttonWithType: method.
Second, there is no button color. You can set a color for title with setTitleColor:forState: method.
There are just syntax mistakes in your code (UIButton.text, etc). You cant do such a call. UIButton is a class.
Your calling createIndexButtonWithNumber... within for will place buttons in the same place — atPosition input parameter has no change.
NSInteger variable is not a pointer — * is not needed.
...
In the end of struggling we have smth like that:
-(void)createIndexButtonWithNumber:(NSInteger)bNumber //(sorry for that, some troubles with code formatting)
withTitle:(NSString *)bTitle
atPosition:(NSInteger)bPosition
withColour:(NSInteger)bColour {
CGRect buttonFrame = CGRectMake(0,bPosition,25,25);
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = buttonFrame;
button.tag = bNumber;
[button setTitle: [NSString stringWithFormat:#"Button %i", bNumber]
forState:UIControlStateNormal];
if (bColour == 1) {
[button setTitleColor:[UIColor colorWithRed:0.751 green:0.742 blue:0.715 alpha:1.000]
forState:UIControlStateNormal];
};
// you should pass to #selector a description like 'indexAction:' but NOT any calls like '[self indexAction:button]'
[button addTarget:self
action:#selector(indexAction:)
forControlEvents:UIControlEventTouchUpInside];
[indexView addSubview:button];
}
And for call:
for (int temp = 0; temp < 2; temp++) {
[self createIndexButtonWithNumber:temp withTitle:[#"Test%i", temp] atPosition:30 * temp withColour:1];
}
UPDATE: Selector method
-(void)indexAction:(id)sender {
NSLog(#"Button with tag %d is pressed", ((UIButton *)sender).tag);
}

how to resize the button image in iphone

im new in iphone.now im developing button image view in iphone.here images are images displaying large size i want to resize the images. that means images are displayed like medium size. i implement code like this.
images = [[NSMutableArray alloc]init];
[images addObject:[UIImage imageNamed:#"bearlarge.jpg"]];
[images addObject:[UIImage imageNamed:#"bufflo_large.jpg"]];
[images addObject:[UIImage imageNamed:#"camel_large.jpg"]];
UIView *view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
int row = 0;
int column = 0;
for(int i = 0; i < images.count; ++i) {
// UIImage *thumb = [images objectAtIndex:i];
UIButton * button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(column*105+14, row*105+10, 50,50);
[button setImage:[images objectAtIndex:i] forState:UIControlStateNormal];
[button addTarget:self
action:#selector(buttonClicked:)
forControlEvents:UIControlEventTouchUpInside];
button.tag = i;
[view addSubview:button];
if (column == 2) {
column = 0;
row++;
} else {
column++;
}
}
//[view setContentSize:CGSizeMake(320, (row+1) * 80 + 10)];
self.view = view;
[view release];
can any one plz send me code for how to resize the button images in iphone.
Thank you in advançe.
You could create this category for UIImage:
- (UIImage *)rescaleImageToSize:(CGSize)size {
CGRect rect = CGRectMake(0.0, 0.0, size.width, size.height);
UIGraphicsBeginImageContext(rect.size);
[self drawInRect:rect]; // scales image to rect
UIImage *resImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resImage;
}
Better add a UIImageView over the button. So that you can easily change the frame size.
CODE
UIButton *imageBut=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
UIImageView *img=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
img.userInteractionEnabled=NO;
[imageBut addSubview:img];
[self.view addSubview:imageBut];
[imageBut release];
[img release];
Or else, use
[button setBackgroundImage:YourImage];
setImage will set the image with original size in which you are included that into your project.
setBackgroundImage will resize the original image.
[button setBackgroundImage:[images objectAtIndex:i] forState:UIControlStateNormal];
-(void)scaleImage:(id)sender
{
if([(UIPinchGestureRecognizer*)sender state] == UIGestureRecognizerStateEnded)
{
lastScale = 1.0;
return;
}
CGFloat scale = 1.0 - (lastScale - [(UIPinchGestureRecognizer*)sender scale]);
CGAffineTransform currentTransform = [(UIPinchGestureRecognizer*)sender view].transform;
CGAffineTransform newTransform = CGAffineTransformScale(currentTransform, scale, scale);
[[(UIPinchGestureRecognizer*)sender view] setTransform:newTransform];
lastScale = [(UIPinchGestureRecognizer*)sender scale];
}

Custom button in tabbar problem

I've a TabBarController Application.
This code in didFinishingLaunching method:
UIImage *buttonImage = [UIImage imageNamed:#"post-button2.png"];
UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
NSLog(#"Button size: %f, %f", buttonImage.size.width, buttonImage.size.height);
button.frame = CGRectMake(0.0, 0.0, buttonImage.size.width, buttonImage.size.height);
[button setBackgroundImage:buttonImage forState:UIControlStateNormal];
CGFloat heightDifference = buttonImage.size.height - self.tabBarController.tabBar.frame.size.height;
NSLog(#"self.tabBarController.tabBar.frame.size.height: %f", self.tabBarController.tabBar.frame.size.height);
NSLog(#"heightDifference: %f", heightDifference);
NSLog(#"%Tabbar: %f, %f", tabBarController.tabBar.center.x, tabBarController.tabBar.center.y);
if (heightDifference < 0)
button.center = tabBarController.tabBar.center;
else {
CGPoint center = self.tabBarController.tabBar.center;
center.y = center.y - heightDifference/2.0;
button.center = tabBarController.tabBar.center;
}
NSLog(#"%Button: %f, %f", button.center.y, button.center.x);
[tabBarController.view addSubview:button];
[self.window addSubview:tabBarController.view];
[self.window makeKeyAndVisible];
The output is:
Where is the problem? I can solve with hardcoded code:
CGPoint center = tabBarController.tabBar.center;
center.x = 160.00;
center.y = 455.50;
button.center = center;
But I'm not sure that is correct.
Ty.
To set the image of a tab you need to set the tabBarItem of the viewcontroller associated with the tab.
See UITabBarItem ref for how to create one with custom image.
So you create a UITabBarItem object with the custom image and then make it the tabBarItem property of the viewcontroller for the tab.
The UITabBarController will then manage putting the image in the right place.