2011-10-20 13 views
0

我創建5個按鈕動態的位置,如下所示:確定一個UIButton

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

在任何按鈕的Click事件,我想找到我已單擊該按鈕的位置。 ...

-(void)checkboxButton:(UIButton*)sender 
{ 
    NSLog(@"%d",xpos); 
} 

但是,它只顯示最後一個按鈕的xpos ......有什麼辦法通過它的標籤來識別它嗎?

回答

0

我把它XPOS是一個全局變量 - 當然,它包含了最後一個按鈕的價值,這就是它被設置爲持續的價值。

對於按鈕位置,您不需要在全局變量中存儲任何東西 - 只需從發送者對象中獲取它,然後在click事件處理程序中將它傳遞給您 - 它是UIButton指針,並且UIButton對象具有的幀結構與origin.x和origin.y,以及一個size.width和size.height,順便。

+0

由於它工作正常.... – Icoder

1

試試這個:

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

你可以試試這個...

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