[英]How to set alignment for UIScrollView in ios
我正在创建一个应用程序,其中使用UIScrollView来显示每种产品的可用颜色数量。 我在运行时得到了可用颜色的数量,因此我已经习惯了循环并在滚动视图上显示。 它的工作正常,但问题是,如果我仅获得一种可用颜色,则输出如下屏幕所示:
但是输出应该如下图所示:
似乎我需要为UIScrollView进行某种中心对齐,因此每种可用颜色都应该从中心显示。 这是我的代码:
UIScrollView *availableColorScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 80)];
availableColorScrollView.backgroundColor = [UIColor clearColor];
availableColorScrollView.showsHorizontalScrollIndicator = YES;
availableColorScrollView.showsVerticalScrollIndicator=NO;
availableColorScrollView.pagingEnabled = YES;
for (int i = 0; i < arrayAvlbleColors.count; i++) {
CGRect frame;
frame.origin.x = 23 * i;
frame.origin.y = 0;
frame.size = availableColorScrollView.frame.size;
UIView *subview = [[UIView alloc] initWithFrame:frame];
UILabel *label = [[UILabel alloc] init];
[label setFrame:CGRectMake(15, 14, 16, 16)];
[label.layer setCornerRadius:8];
NSString *strColorCode = [arrayAvlbleColors objectAtIndex:i];
strColorCode = [strColorCode substringFromIndex:1];
[label setBackgroundColor:[self colorWithHexString:strColorCode]];
[subview addSubview:label];
[availableColorScrollView addSubview:subview];
}
[self.view addSubview:availableColorScrollView];
availableColorScrollView.contentSize = CGSizeMake(24 * arrayAvlbleColors.count, availableColorScrollView.frame.size.height);
请建议我实现输出,谢谢!
您可以这样计算滚动视图内容,使其位于中心:
float contentWidth = 23 * arrayAvlbleColors.count;
现在您有内容宽度要从scrollView的宽度中减去
float centerPadding = 0.0f;
float width = availableColorScrollView.frame.size.width;
centerPadding = width - contentWidth;
if(centerPadding < 0)
{
//content cannot be placed in center as content is bigger than width
centerPadding = 0.0f;
}
我们需要填充以使我们的内容在scrollView中居中,因此可以在for循环中使用它,如下所示:
frame.origin.x = (23 * i) + centerPadding;
这是简单的答案,但是如果您使用了任何Mainview
subview
或subview
,都可以正常工作,否则,将frame size/2
为height
和width
它会自动将其设置为subview
center
。
在这里我用了静态色彩,自己定制
只是改变你的线
NSString *strColorCode = [arrayAvlbleColors objectAtIndex:i];
strColorCode = [strColorCode substringFromIndex:1];
[label setBackgroundColor:[self colorWithHexString:strColorCode]];
[subview addSubview:label];
[availableColorScrollView addSubview:subview];
进入
NSString *strColorCode = [arrayAvlbleColors objectAtIndex:i];
strColorCode = [strColorCode substringFromIndex:1];
[label setBackgroundColor:[self colorWithHexString:strColorCode]];
//use any one
//option no 1:
//[label setCenter:subview.center];
//option no 2:
[ label setCenter:CGPointMake(subview.frame.size.width / 2, subview.frame.size.height / 2)];
[subview addSubview:label];
[availableColorScrollView addSubview:subview];
最后输出是
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.