UIScrollView 按钮分页



我一直在尝试制作一个 100x100 像素的滚动视图(分页模式),以每页 75x75 的速度显示一个按钮。我可以显示第一个图像,但我无法分页到下一个图像。这是我一直在使用的代码,有人可以帮我吗?

.h

@property (nonatomic , retain) IBOutlet UIScrollView *scrollMenu;

.m

@synthesize scrollMenu;
-(void)viewDidLoad {
scrollMenu.pagingEnabled = YES;
NSInteger numberOfButtons = 2;
for (int i = 0; i < numberOfButtons; i++) {
    //Array of images for the buttons
    NSArray *menuItems = [[NSArray alloc] initWithObjects:[UIImage imageNamed:@"1.png"], [UIImage imageNamed:@"2.png"], nil];
    //Create A Button
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    //Give the button an action
    [button addTarget:self action:@selector(menuItemSelected:) forControlEvents:UIControlEventTouchUpInside];
    //Give the button an image
    [button setImage:[menuItems objectAtIndex:i] forState:UIControlStateNormal];
    //Most likely WRONG
    button.frame = CGRectMake(i*(20+75), 8.0, 75, 75);

    button.showsTouchWhenHighlighted=YES;
    //Assign a tag
    button.tag = i;
    //Add the button to the view
    [scrollMenu addSubview:button];
}
//Most likely WRONG
scrollMenu.contentSize = CGSizeMake(100,100);
[self.view addSubview:scrollMenu];
 }
  [super viewDidLoad];
}

我已经实现了类似的东西,但对于UIImageView。这里你只需要设置 UI ScrollView 的一些属性,并且需要实现一个委托方法。

首先设置一些属性

- (void)viewDidLoad
{
    [super viewDidLoad];
    _scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;
    _scrollView.multipleTouchEnabled=YES;
    _scrollView.scrollEnabled=YES;
    _scrollView.directionalLockEnabled=YES;
    _scrollView.canCancelContentTouches=YES;
    _scrollView.delaysContentTouches=YES;
    _scrollView.clipsToBounds=YES;
    _scrollView.alwaysBounceHorizontal=YES;
    _scrollView.bounces=YES;
    _scrollView.pagingEnabled=YES;
    _scrollView.showsVerticalScrollIndicator=NO;
    _scrollView.showsHorizontalScrollIndicator=NO;
    _scrollView.delegate=self;
}

实现委托方法

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    @try
    {
        CGFloat pageWidth = 320;    //scrollView.frame.size.width;
        int page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
        if (page >9)
            page = page - 3;
        if (page <[listOfPictures count])
        {
            [_scrollView setContentOffset:CGPointMake(320*page, _scrollView.contentOffset.y) animated:YES];
            currentPicIndex = page;
        }
    }
    @catch (NSException *exception)
    {
        TRACE_ERROR(@"scrollViewDidEndDecelerating", exception.name, exception.description);
    }
}

我的滚动视图是240X300。因此,请使用按钮像素进行操作,滚动视图并像明智地设置内容偏移集。

希望这能帮助你。

最新更新