我会做这样的事情:拥有一个 UIImageView 和一个视图控制器。视图控制器有一个 NSArray,比如buttonsOnPage。在数组内部,您将存储更多 NSArrays 存储按钮。这些按钮都指向同一个操作,例如buttonPressed:。请记住,您可以分配tags,您可以使用这些来确定要转到哪个“页面”。由于加载您的图像似乎很简单,我在这里跳过。
这是一个小伪代码:
- (void)initButtons
{
NSMutableArray *page;
UIButton *button;
buttonsOnPage = [[NSMutableArray alloc] init];
// Page 0
page = [NSMutableArray array];
button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self action:@selector(buttonPressed:) forControlEvent:UIEventTouchUpInside];
[button setTag:5]; // When pressed, go to page 5.
[button setFrame:...];
[page addObject:button];
...
[buttonsOnPage addObject:page];
...
}
- (void)setUpPage:(NSUInteger)page
{
// Remove all previous buttons
for (UIView *view in [myImageView subviews]) {
[view removeFromSuperview];
}
for (UIButton *button in [buttonsOnPage objectAtIndex:page]) {
[myImageView addSubview:button];
}
// Also set the correct image.
}
- (void)buttonPressed:(id)sender
{
[self setUpPage:[(UIView *)sender tag]];
}
您可以通过定义宏使您的按钮设置方法更容易/更快地键入:
#define NEW_BUTTON(page, x, y, width, height) \
do {
button = [UIButton buttonWithType:UIButtonTypeCustom]; \
[button addTarget:self action:@selector(buttonPressed:) forControlEvent:UIEventTouchUpInside];\
[button setTag:page]; \
[button setFrame:CGRectMake(x, y, width, height)]; \
[page addObject:button];
} while (0);
那么做起来还是挺快的:
// Page 0
page = [NSMutableArray array];
NEW_BUTTON(1, 10, 20, 20, 20);
NEW_BUTTON(2, 10, 60, 20, 20);
[buttonsOnPage addObject:page];
// Page 1
page = [NSMutableArray array];
NEW_BUTTON(3, 70, 20, 20, 20);
NEW_BUTTON(4, 10, 160, 20, 20);
[buttonsOnPage addObject:page];
...