我已经在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 :(得分:3)
如果要以编程方式移动scrollview而不是
[scrollView scrollRectToVisible:selectedBtn.bounds animated:YES];
尝试这个
scrollView.contentOffset = selectedBtn.frame.origin;
答案 1 :(得分:0)
试试这个
确保在scrollView中设置以下内容。
scrollView.delaysContentTouches = NO;
希望它有所帮助。