嗨恶魔我是ios app dev的新手。我遇到了一个简单的问题,在我的应用程序中,我添加了水平滚动的UIScrollView。我已经为该滚动视图添加了动态更改的按钮。代码是
Step 1:
scroll = [[UIScrollView alloc]init];
scroll.delegate=self;
scroll.frame = CGRectMake(0, 0, 320, (height+25));
[scroll setContentSize:CGSizeMake((width-30)*n, height+25)];
scroll.backgroundColor=[UIColor clearColor];
scroll.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"GP-BG.png"]];
scroll.showsHorizontalScrollIndicator=NO;
scroll.alwaysBounceHorizontal=NO;
for(int i=0;i<n;i++)
{
MODELRoom *room = [self.resultSet.dataObjectList objectAtIndex:i];
CGRect rectForTitleButton = CGRectMake(i*(width-30), 0, width-30, height+25);
int buttonTag =10000+i;
UIButton *titleButton = [self getRoomButton:room tag:buttonTag];
titleButton.tag=buttonTag;
[titleButton setFrame:rectForTitleButton];
titleButton.backgroundColor=[UIColor clearColor];
[scroll addSubview:titleButton];
[controlButtons addObject:titleButton];
}
}
step 2:
- (UIButton*)getRoomButton:(MODELRoom *)currenRoom tag:(int)tagValue{
UIButton *button=[[UIButton alloc] init];
[button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
UIImage *buttonImageNormal;
if(currenRoom.currentlySelected){
buttonImageNormal=[UIImage imageNamed:[NSString stringWithFormat:@"GP-BG-Slected Green.png"]];
}else{
buttonImageNormal=[UIImage imageNamed:[NSString stringWithFormat:@""]];
}
[button setBackgroundImage:buttonImageNormal forState:UIControlStateNormal];
[gridViewObjects addObject:button];
return button;
}
step 3:
- (void)buttonClicked:(UIButton *)sender{
if((int)[sender tag]>=10000 && (int)[sender tag]<20000){
currentRoom=((MODELRoom*)[resultSet.dataObjectList objectAtIndex:[sender tag]-10000]);
[self roomSelectionChanged:currentRoom];
currentRoom.currentlySelected=true;
scrollStrech=(width-30)*([sender tag]-10000);
scroll.contentOffset=CGPointMake(scrollStrech, 0);
NSLog(@"Scroll Strech=%d",scrollStrech);
for(int i=0;i<[resultSet.dataObjectList count];i++){
if(![[resultSet.dataObjectList objectAtIndex:i] isEqual:currentRoom]){
((MODELRoom*)[resultSet.dataObjectList objectAtIndex:i]).currentlySelected=false;
}
}
[self refresh];
}
step 4:
-(void)refresh{
if([self.scroll isDescendantOfView:self.view]){
[self.scroll removeFromSuperview];
}
}
每件事情都很好但是当我选择滚动后可见的第五个或第六个按钮时,如果我选择该按钮,则滚动视图会重新弹回到第一个位置。我发现这可以从superview中删除并再次加载它。如果是这种情况,我还需要在所选按钮区域显示滚动视图区域。
请建议我如何克服这个......
答案 0 :(得分:0)
在buttonClicked上尝试此操作
CGRect rect= CGRectMake(sender.frame.origin.x, sender.frame.origin.y , sender.frame.size.width, sender.frame.size.height);
[scrollView scrollRectToVisible:rect animated:YES];