前一篇的改進版,加入圖片X/Y方向的聯結,並使用ScrollView提供滑動的視覺效果。
1. 從前一篇改進過來,多一個ScrollView,並以上下的方式排列。
2. 對這兩個ScrollView註冊到ScrollViewController.h
3. 對ScrollViewController.m修改如下
#import "ScrollViewController.h"
const CGFloat kScrollObjHeight = 199.0;
const CGFloat kScrollObjWidth = 280.0;
const NSUInteger kNumImages = 3;
@interface ScrollViewController ()
@end
@implementation ScrollViewController
@synthesize myScrollView1;
@synthesize myScrollView2;
- (void)layoutScrollImages
{
UIImageView *view = nil;
NSArray *subviews = [myScrollView1 subviews];
// reposition all image subviews in a horizontal serial fashion
CGFloat curXLoc = 0;
for (view in subviews)
{
if ([view isKindOfClass:[UIImageView class]] && view.tag > 0)
{
CGRect frame = view.frame;
frame.origin = CGPointMake(curXLoc, 0);
view.frame = frame;
curXLoc += (kScrollObjWidth);
}
}
NSInteger height = [myScrollView1 bounds].size.height;
// set the content size so it can be scrollable
[myScrollView1 setContentSize:CGSizeMake((kNumImages * kScrollObjWidth), height)];
UIImageView *view1 = nil;
NSArray *subviews1 = [myScrollView2 subviews];
// reposition all image subviews in a horizontal serial fashion
CGFloat curXLoc1 = 0;
for (view1 in subviews1)
{
if ([view1 isKindOfClass:[UIImageView class]] && view1.tag > 0)
{
CGRect frame = view1.frame;
frame.origin = CGPointMake( 0, curXLoc1);
view1.frame = frame;
curXLoc1 += (kScrollObjHeight);
}
}
NSInteger width = [myScrollView2 bounds].size.width;
// set the content size so it can be scrollable
[myScrollView2 setContentSize:CGSizeMake(width, (kNumImages * kScrollObjHeight))];
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSUInteger i;
for (i = 1; i <= kNumImages; i++)
{
NSString *imageName = [NSString stringWithFormat:@"TaiwanMap.jpg", i];
UIImage *image = [UIImage imageNamed:imageName];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
// setup each frame to a default height and width, it will be properly placed when we call "updateScrollList"
CGRect rect = imageView.frame;
rect.size.height = kScrollObjHeight;
rect.size.width = kScrollObjWidth;
imageView.frame = rect;
imageView.tag = i; // tag our images for later use when we place them in serial fashion
[myScrollView1 addSubview:imageView];
// [myScrollView2 addSubview:imageView];
// [imageView release];
}
for (i = 1; i <= kNumImages; i++)
{
NSString *imageName = [NSString stringWithFormat:@"TaiwanMap.jpg", i];
UIImage *image = [UIImage imageNamed:imageName];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
// setup each frame to a default height and width, it will be properly placed when we call "updateScrollList"
CGRect rect = imageView.frame;
rect.size.height = kScrollObjHeight;
rect.size.width = kScrollObjWidth;
imageView.frame = rect;
imageView.tag = i; // tag our images for later use when we place them in serial fashion
[myScrollView2 addSubview:imageView];
// [imageView release];
}
[self layoutScrollImages];
}
4. 完成後的結果如圖,



