我有一个 scrollView
,上面有很多按钮。我试图从滚动中获取按钮位置,以便我可以将其滚动到该位置。我的问题是,单击每个按钮后,我总是在 _btnV.frame.origin.x
中获得相同的值。那么请问我该如何解决这个问题?
- (void)scrollView{
segmentWidth = screenWidth / 5;
NSArray *images = @[@"Smiley-1.png",@"Smiley-2.png",@"Smiley-3.png",@"Smiley-4.png",@"Smiley-5.png",@"Smiley-5.png",@"Smiley-5.png",@"Smiley-4.png",@"Smiley-1.png",@"Smiley-2.png",@"Smiley-3.png",@"Smiley-4.png"];
long ScrollContentSize = ((images.count -1)*segmentWidth)+screenWidth;
_scrlView.contentSize = CGSizeMake(ScrollContentSize, _scrlView.frame.size.height);
float screenX2 = screenHeight/2 - segmentWidth/2;
__block float screenX = (screenWidth-segmentWidth)/2;
NSMutableArray *arr = [[NSMutableArray alloc] init];
for(int i=0; i<images.count; i++)
{
_btnV = [[UIButton alloc]init];
[_btnV setFrame:CGRectMake(screenX, screenX2, segmentWidth, segmentWidth)];
[_btnV setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@",[images objectAtIndex:i]]] forState:UIControlStateNormal];
[_btnV setBackgroundColor:[UIColor redColor]];
[_btnV addTarget:self action:@selector(scrollToMe:) forControlEvents:UIControlEventTouchUpInside];
[_btnV setTag:i];
[arr addObject:_btnV];
[_scrlView addSubview:_btnV];
screenX = screenX+segmentWidth;
}
_menuItems = arr;
[self.view addSubview:_scrlView];
}
-(void) scrollToMe:(id)sender{
int scrollX = _scrlView.contentOffset.x;
int mod = scrollX % segmentWidth;
int position = scrollX/segmentWidth;
float positionOffset = (float) mod / segmentWidth;
scrollX = position * segmentWidth;
NSLog(@"position:%f",_btnV.frame.origin.x);
//scrollX = ...
[_scrlView setContentOffset:CGPointMake(scrollX, scrollX) animated:YES];
}
最佳答案
使用标签值找到按钮
-(void) scrollTo:(id)sender{
UIButton * button = (UIButton *)sender;
int position = button.tag;
scrollX = position * segmentWidth;
NSLog(@"position:%f",_btnV.frame.origin.x);
//scrollX = ...
[_scrlView setContentOffset:CGPointMake(scrollX, scrollX) animated:YES];
}
关于ios - 如何从 UIScrollView 获取 UIButton 位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29820256/