IOS获得位置
我有一个UIScrollView里面有很多的button,我试图让他们的位置button点击。 这是我的代码:
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];
和
-(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",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); }
但我也是一样的。
你的代码看起来很好。 唯一的 – 你在NSLog中使用错误的格式说明符。 由于坐标是浮点数,您应该使用%f
而不是%d
:
NSLog(@"position:%f",buton1.frame.origin.x);
如果使用scrollRectToVisible:animated:
方法,则有一个技巧,因为文档说:此方法滚动内容视图,以便rect定义的区域在滚动视图内可见。 如果该区域已经可见,则该方法什么都不做。
尝试滚动到CGRectMake(buton1.frame.origin.x, buton1.frame.origin.y, yourScrollView.frame.width, yourScrollView.frame.height)
。
你可以在第三个参数上使用模糊因子。