
画面より大きいViewをスクロールさせて表示するにはUIScrollViewを使う。
サンプルViewは前回のDrawRectViewを使い回し。
【DrawRectViewの定義】
@interface DrawRectView : UIView {
}
@end
@implementation DrawRectView
- (id)init{
self = [super init];
return self;
}
- (void)drawRect:(CGRect)rect{
CGContextRef g = UIGraphicsGetCurrentContext();
CGContextSetRGBFillColor(g, 1.0, 1.0, 1.0, 1.0);
CGContextFillRect(g, CGRectMake(0, 0, self.frame.size.width, self.frame.size.height));
CGContextSetRGBFillColor(g, 1.0, 0.0, 0.0, 1.0);
CGContextFillRect(g, CGRectMake(self.frame.size.width*0.1, self.frame.size.height*0.1, self.frame.size.width*0.8, self.frame.size.height*0.8));
CGContextSetRGBFillColor(g, 0.0, 0.0, 1.0, 1.0);
CGContextFillRect(g, CGRectMake(self.frame.size.width*0.2, self.frame.size.height*0.2, self.frame.size.width*0.6, self.frame.size.height*0.6));
CGContextSetRGBStrokeColor(g, 0.0, 0.0, 0.0, 1.0);
CGContextBeginPath(g);
CGContextMoveToPoint(g, 0, 0);
CGContextAddLineToPoint(g, self.frame.size.width, self.frame.size.height);
CGContextMoveToPoint(g, self.frame.size.width, 0);
CGContextAddLineToPoint(g, 0, self.frame.size.height);
CGContextClosePath(g);
CGContextDrawPath(g, kCGPathStroke);
}
@end
ビューのサイズ全体に対して、
白い四角、ちょっと小さい赤い四角、さらに小さい青い四角、全体に×が
描かれます。
これを組み込みます。
UIView* oya = [[UIView alloc]init];
oya.frame = CGRectMake(0, 0, 320, 480);
UIScrollView* sc = [[UIScrollView alloc]init];
sc.frame = CGRectMake(0, 0, 320, 480);
[oya addSubview:sc];
DrawRectView* view = [[DrawRectView alloc]init];
view.frame = CGRectMake(0, 0, 1000, 1000);
[sc addSubview:view];
[sc setContentSize:CGSizeMake(1000, 1000)];
今回は、でっかく1000x1000に広げたDrawRectViewをスクロールの中にいれました。
UIScrollViewはUIViewのサブクラスなので、ViewにaddSubviewします。
そのなかに、スクロールさせたいものを入れるには、
1)UIScrollViewにaddSubviewする
2)setContentSizeでスクロール領域を設定する
の2つを実行する。
これだけでおしまい。ちゃーんとスクロールしてくれます。
ラクチン便利ですねー

