1

嗨恶魔我是 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];
}

}

一切正常,但是当我选择滚动后可见的第五个或第六个按钮时,如果我选择该按钮,滚动视图将反弹到第一个位置。我发现这是因为从超级视图中删除并再次加载它。如果是这种情况,我也只需要在该选定按钮区域显示滚动视图区域。

请建议我如何克服这个....

4

1 回答 1

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];
于 2013-06-25T12:36:36.833 回答