Icoder
Icoder

Reputation: 330

Identifying the Position of a UIButton

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?

Upvotes: 0

Views: 290

Answers (3)

TheEye
TheEye

Reputation: 9346

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.

Upvotes: 0

Sahil Khanna
Sahil Khanna

Reputation: 4382

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);
}

Upvotes: 0

Maulik
Maulik

Reputation: 19418

try this :

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

Upvotes: 1

Related Questions