ios: UIScrollView scrollRectToVisible 不工作

标签 ios objective-c uiscrollview

我在 scrollView 上动态添加了一些按钮

`int separotorWidth=2;


  [scrollView setContentSize:CGSizeMake(noOfTabs*100+(separotorWidth*(noOfTabs-1)),0)];
    UIView* tabHolder=[[UIView alloc] initWithFrame:CGRectMake(0, 0, noOfTabs*100+(separotorWidth*(noOfTabs-1)), scrollView.frame.size.height)];

   int x=0;
    for (int i=0; i<noOfTabs; i++) {
        UIButton* tab= [[UIButton alloc] initWithFrame:CGRectMake(x, 0, 100, scrollView.frame.size.height)];
        [tab setTag:i];
        x=(x+100)+separotorWidth;
        [tab setTitle:[NSString stringWithFormat:@"%@",[tabTitles objectAtIndex:i]] forState:UIControlStateNormal];
        tab.titleLabel.lineBreakMode=NSLineBreakByWordWrapping;
        tab.titleLabel.textAlignment=NSTextAlignmentCenter;
        tab.titleLabel.font=[UIFont systemFontOfSize:11];
        [tab setBackgroundColor:[ViewUtil blueColor]];

        [tab addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];

        [tabHolder addSubview:tab];
        if (i==5) { //say 5th tab
            selectedBtn=tab;
        }
    }
    [scrollView addSubview:tabHolder];`

我想以编程方式滚动 ScrollView 以确保第 5 个按钮可见。我尝试了以下方法,但没有用 [scrollView scrollRectToVisible:selectedBtn.bounds animated:YES];

请提供最好的方法。

编辑:回答

 if ((selectedBtn.frame.origin.x+selectedBtn.frame.size.width)>(scrollView.frame.origin.x+scrollView.frame.size.width)) {

        CGPoint btnRightTopCorner= selectedBtn.frame.origin;
        CGPoint btnleftTopCorner=btnRightTopCorner;
        btnleftTopCorner.x=btnleftTopCorner.x+selectedBtn.frame.size.width;
        CGPoint contentRightTopConer=btnleftTopCorner;
        contentRightTopConer.x=contentRightTopConer.x-scrollView.frame.size.width;

        scrollView.contentOffset = contentRightTopConer;

    }

最佳答案

如果你想以编程方式移动 ScrollView 而不是

[scrollView scrollRectToVisible:selectedBtn.bounds animated:YES];

试试这个

scrollView.contentOffset = selectedBtn.frame.origin;

关于ios: UIScrollView scrollRectToVisible 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31786169/

相关文章:

ios - UISwitch 没有反应

ios - UIPickerView pickerView :titleForRow:rowforComponent method not called

iphone - 从 UIScrollView 中删除 subview

ios - Firebase - 在 .delete() 之后清除缓存的订阅

iOS 9 快速操作 (3D Touch)

ios - 无法将类型 'UITableViewCell' 的值转换为 'SwipeCellKit.SwipeTableViewCell'

iphone - 具有自动布局的 UIScrollView 无法按预期工作

ios - 重置 box-sizing 对 iOS safari web 有什么危害吗?

iphone - 为 iphone 应用程序设置自动构建服务器的最佳实践?

ios - 为同一类中的 2 个不同 UIScrollView 设置委托(delegate)