带有 UIButtons 的无限水平 UIScrollView

Posted

技术标签:

【中文标题】带有 UIButtons 的无限水平 UIScrollView【英文标题】:Infinite horizontal UIScrollView with UIButtons 【发布时间】:2013-08-12 06:46:00 【问题描述】:

这就是我目前所做的。

scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(56, 205, 400, 3000)];
scrollView.delegate = self;
scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * 3.0f,scrollView.frame.size.height * 3.0f);
scrollView.maximumZoomScale = 3.0f;

UIView *zoomView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, scrollView.contentSize.width, scrollView.contentSize.height)];
zoomView.backgroundColor = [UIColor whiteColor];
for (NSInteger index = 0; index < 100; index++)

    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake((scrollView.frame.size.width / 2.0f) - 50.0f, 10.0f + (50.0f * (CGFloat)index), 100.0f, 30.0f);
    button.tag = index;
    [button setTitle:[NSString stringWithFormat:@"Button %ld", ((long)index + 1)] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(didTapButton:) forControlEvents:UIControlEventTouchUpInside];

    [zoomView addSubview:button];


[scrollView addSubview:zoomView];
[self.view addSubview:scrollView];

问题是。它不是无限的。我希望数字 101 是数字 1,希望你能理解。我如何动态地创建它们,通过网络服务告诉我我将拥有多少按钮,我应该为每个按钮应用什么背景,以及在按钮下放置什么文本。上面的代码也是垂直滚动的,但最后它会是一个非缩放的水平滚动视图。提前致谢。

【问题讨论】:

你想滚动你的 UIScrollview 直到 zoomView 帧大小吗? 【参考方案1】:

只需设置滚动视图的内容大小

scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(56, 205, 400, 320)]; // it is for iphone. set it's resolution if you want to set it for ipad
scrollView.delegate = self;
scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * 3.0f,scrollView.frame.size.height * 3.0f);
scrollView.maximumZoomScale = 3.0f;

UIView *zoomView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, scrollView.contentSize.width, scrollView.contentSize.height)];
zoomView.backgroundColor = [UIColor whiteColor];
for (NSInteger index = 0; index < 100; index++)

    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake((scrollView.frame.size.width / 2.0f) - 50.0f, 10.0f + (50.0f * (CGFloat)index), 100.0f, 30.0f);
    button.tag = index;
    [button setTitle:[NSString stringWithFormat:@"Button %ld", ((long)index + 1)] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(didTapButton:) forControlEvents:UIControlEventTouchUpInside];

    [zoomView addSubview:button];


[scrollView addSubview:zoomView];
[self.view addSubview:scrollView];

scrollView.contentSize= CGSizeMake((zoomView.frame.size.width) , zoomView.frame.size.height);

在将缩放视图添加到滚动视图后设置它。 希望能帮助你理解。

【讨论】:

以上是关于带有 UIButtons 的无限水平 UIScrollView的主要内容,如果未能解决你的问题,请参考以下文章

水平 UIScrollView 和一堆 UIButtons

将 UIButtons 添加为子视图时 UIScrollView 不滚动

一个无限的水平翻转动画 ImageWidget Flutter

在 UIScrollView 中居中 UIButtons

带有改变大小的 UIButtons 的 iOS 回流布局

带有 UIButtons 的 UIScrollview - 如何重新创建跳板?