0

我一直在尝试制作一个 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];
}
4

1 回答 1

0

我已经实现了类似的东西,但对于 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。因此,请使用按钮、滚动视图的像素进行操作,并明智地设置 ContentOffSet。

希望这可以帮助你。

于 2013-02-02T06:27:58.990 回答