【发布时间】:2015-08-03 11:33:54
【问题描述】:
我在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];`
我想以编程方式滚动滚动视图以确保第 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;
}
【问题讨论】:
-
滚动视图框架为 (0,0,350,50)。
-
编辑:答案将像 scrollRectToVisible 一样工作
标签: ios objective-c uiscrollview