答えは、実際には他の多くの答えとコメントの組み合わせと、その他の調整です。
- Pan が言ったように、scrollView デリゲートを設定する必要があります。そうしないと、viewForZoomingInScrollView: デリゲートの実装が呼び出されません。この呼び出しを viewDidLoad: で提供しましたが、これをインターフェイス ビルダーまたはストーリーボードに接続することもできます。
- Teodor Carstea が元の投稿へのコメントで述べたように、元のコードでは、あなた
.imageView.size
とあなた
.scrollView.contentsSize
をまったく同じものに設定しています。.imageView.frame.
の一部として発生する
を設定するコードは必要ありませんinitWithImage:
。これにより、サイズが異なります。
.scrollView.contentSize
を に設定する必要がありますimage.size
。どこでこれを行うかは、少なくともズームスケールを設定する前に行う必要があるという点で重要です。
- Kunal Balani が述べたように、ストーリーボードまたはインターフェイス ビルダーで設定できますが、scrollingEnabled が必要です。
- MidhunMP が言ったように、必要がありますが
.userInteractionEnabled = YES
、一般的に、これらはストーリーボード/Interface Builder で設定されるデフォルトであるため、以下のコード変更には含めません。
- あなたのメソッド
centerScrollViewContents
は、 imageViewフレームを再形成しているので、実際にはコンテンツを中央に配置していません。完全に不要だと思うので、呼び出しをコメントアウトしただけです。代わりに、画像を左上隅から開始するための簡単な呼び出しを行いました。
- スクロールするだけの場合は
zoomScale
、minimumZoomScale
と を
設定するmaximumZoomScale
必要はありません。ピンチズームも行う場合は、これら 3 つすべてを適切な場所に設定する必要があります。
- ビューがコンテンツの境界よりも小さい場合は、ビューを引き伸ばしたいようです。これが本当に問題である場合 (つまり、bg.png が小さすぎて引き伸ばす必要があることがわかっている場合)、contentFrame と画像フレームの幅の比率と高さの比率を別々に計算し、これらのいずれか大きい方が新しいものになります。 zoomScale を使用すると、反対方向にスクロールできます。または、そのスケール セットをどのように使用するかを決定する他の方法があります。必要に応じてズームスケールを設定するための他の回答については、stackoverflow.com を検索してください。
これらの項目を適用した後のコードは次のとおりです。
(void)viewDidLoad {
self.scrollView.delegate = self; // can be set in storyboard
self.scrollView.scrollingEnabled = YES; // can be set in storyboard
NSString* bgPng
= [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"bg.png"];
UIImage *image1 = [UIImage imageWithContentsOfFile:bgPng];
self.imageView = [[UIImageView alloc] initWithImage:image1];
// self.imageView.frame = (CGRect){.origin=CGPointMake(0.0f, 0.0f), .size=image1.size};
[self.scrollView addSubview:self.imageView];
self.scrollView.contentSize = image.size;
// set zoom scale here if desired.
// if zoom is implemented, the following call should be made
// after setting .zoomScale, .minimumZoomScale & .maximumZoomScale
self.scrollView.contentOffset = CGPointZero;
// [self centerScrollViewContents];
}
//- (void)centerScrollViewContents {
// CGSize boundsSize = self.scrollView.bounds.size;
// CGRect contentsFrame = self.imageView.frame;
//
// if (contentsFrame.size.width < boundsSize.width) {
// contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0f;
// } else {
// contentsFrame.origin.x = 0.0f;
// }
//
// if (contentsFrame.size.height < boundsSize.height) {
// contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2.0f;
// } else {
// contentsFrame.origin.y = 0.0f;
// }
//
// self.imageView.frame = contentsFrame;
//}
- (UIView*)viewForZoomingInScrollView:(UIScrollView *)scrollView {
// Return the view that you want to zoom
return self.imageView;
}