(伪代码)
contentOffset.x = image.center.x - (screenwidth/2)怎么样
(展开...)
UIImageView* imageView = //imageview that was selected
CGFloat screenWidth = 320;
CGPoint offset = scrollView1.contentOffset;
offset.x = imageView.center.x - screenWidth/2;
[scrollView1 setContentOffset:offset animated:YES];
我假设您已经知道如何获取指向所选图像的指针...
(进一步扩展......)
这是相同的完整版本,使用按钮而不是图像以便于选择...尝试它(只需复制到新的单视图项目的 viewContoller]),您将看到它有效。如果您仍然遇到问题,我希望这是您将图像识别为选定图像以进行居中的方式。您需要更新您的问题以显示您的代码...
- (void)viewDidLoad
{
[super viewDidLoad];
CGRect frame = self.view.bounds;
frame.size.height = frame.size.height/2;
self.scrollView = [[UIScrollView alloc] initWithFrame:frame];
[self.view addSubview:self.scrollView];
[self.scrollView setContentSize:CGSizeMake(2000,self.scrollView.bounds.size.height)];
[self.scrollView setDelegate:self];
for (int i = 1; i < 20; i++) {
UIButton* button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
NSString* title = [NSString stringWithFormat:@"button %d",i];
[button setTitle:title forState:UIControlStateNormal];
button.bounds = CGRectMake(0,0,80,60);
button.center = CGPointMake(i*100+50,self.scrollView.bounds.size.height/2);
[button addTarget:self
action:@selector(buttonPressed:)
forControlEvents:UIControlEventTouchUpInside];
[self.scrollView addSubview:button];
}
}
- (void)buttonPressed:(UIButton*)sender
{
CGFloat x = sender.center.x - self.scrollView.bounds.size.width/2.0f;
[self.scrollView setContentOffset:CGPointMake(x,0) animated:YES];
}