IOS get position

2019-04-11 19:24发布

I have a lot of button inside a UIScrollView and i am trying to get their position on button click. Here is my code:

UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(2, 0, 262, 748)];
scrollView.contentSize=CGSizeMake(262, 816);
scrollView.bounces=NO;
scrollView.delaysContentTouches=YES;

buton1 = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
buton1.frame = CGRectMake(2, 0, 262, 102);
buton1.bounds = CGRectMake(2, 0, 262.0, 102.0);
[buton1 setTag:1];
[buton1 setImage:[UIImage imageNamed:@"left_gride.png"] forState:UIControlStateNormal];
[buton1 addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
     [scrollView addSubview:buton1];

and

-(void) buttonClick:(UIButton*)button{
if ([button tag]==1)
{
     NSLog(@"position:%d",buton1.frame.origin.x);
}
else
{
    NSLog(@"position:%d",buton2.frame.origin.y);
}

}

What is wrong with my code.Thanks.

I also tried with :

-(void) buttonClick:(UIButton*)button{
if ([button tag]==1)
{
     NSLog(@"position:%d",buton1.frame.origin.x);
}
else
{
    NSLog(@"position:%d",buton2.frame.origin.y);
}

-(void) buttonClick:(UIButton*)button{
if ([button tag]==1)
{
     NSLog(@"position:%d",button.frame.origin.x);
}
else
{
    NSLog(@"position:%d",button2.frame.origin.y);
}

But i just get the same.Position 0;

2条回答
三岁会撩人
2楼-- · 2019-04-11 20:15

If you use the scrollRectToVisible:animated: method, there is a trick because the documentation says : This method scrolls the content view so that the area defined by rect is just visible inside the scroll view. If the area is already visible, the method does nothing.

Try to scroll to CGRectMake(buton1.frame.origin.x, buton1.frame.origin.y, yourScrollView.frame.width, yourScrollView.frame.height).

You can use a fudge factor on 3rd parameters.

查看更多
混吃等死
3楼-- · 2019-04-11 20:18

Your code looks fine. The only thing - you use wrong format specifier in NSLog. As coordinates are floating point numbers you should use %f instead of %d:

NSLog(@"position:%f",buton1.frame.origin.x);
查看更多
登录 后发表回答