ios - 如何从 UIScrollView 获取 UIButton 位置

标签 ios objective-c uiscrollview uibutton

我有一个 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/

相关文章:

ios - 如何连续调用以在 Swift 中下拉分页数据

android - 您在哪里提交 Android/iOS Google 产品或服务(AppInvites、 map 等)的错误?

objective-c - 静态 UITableView 不是全屏

ios - 使用动画更改 UIScrollView contentSize

iphone - 将按钮添加到 viewForFooterSection UITableView

ios - Autolayout 和 Scrollview 宽度固定到屏幕(不是内容)

objective-c - 这个 iOS 单例实现的任何潜在缺陷?

ios - 从托管 View Controller 委托(delegate) SwiftUI View

objective-c - 使用 Objective c 将 void *(void * const mAudioData) 转换为 Short *?

html - 在 iOS 7 或 8 的网页 View 中使用不同的样式表