我想在主UIView中水平居中一些UIViews(它们恰好是圆圈)。它最终将基本上看起来像标准页面控件上的点。水平居中多个UIView
我已经编写了所有的代码来创建圆UIViews我只是不知道如何在运行时水平和动态地安排它们。
基本上我需要某种水平的容器在那里我可以做到这一点
-(void)addCircle{
[self addSubView:[CircleView init]];
}
,它会自动安排然而,许多孩子就在中央。
我想在主UIView中水平居中一些UIViews(它们恰好是圆圈)。它最终将基本上看起来像标准页面控件上的点。水平居中多个UIView
我已经编写了所有的代码来创建圆UIViews我只是不知道如何在运行时水平和动态地安排它们。
基本上我需要某种水平的容器在那里我可以做到这一点
-(void)addCircle{
[self addSubView:[CircleView init]];
}
,它会自动安排然而,许多孩子就在中央。
我对自动布局不时感到困惑,不过这里有一种方法可以以编程方式进行:(我假设你将你的圆视图添加到视图控制器的containerView
属性中,添加任何其他意见的话)
这两个属性添加到您的视图控制器:
@property (nonatomic) CGRect circleViewFrame;
@property (nonatomic) CGFloat delta;
发起您的视图控制器的viewDidLoad
方法所需值的属性:
// the size (frame) of your circle views
self.circleViewFrame = CGRectMake(0, 0, 10, 10);
// the horizontal distance between your circle views
self.delta = 10.0;
现在,我们添加 “自动addCircle法”:
- (void)addCircleView {
UIView *newCircleView = [self createCircleView];
[self.containerView addSubview:newCircleView];
[self alignCircleViews];
}
当然,我们需要实现createCircleView
方法...
- (UIView*)createCircleView {
// Create your circle view here - I use a simple square view as an example
UIView *circleView = [[UIView alloc] initWithFrame:self.circleViewFrame];
// Set the backgroundColor to some solid color so you can see the view :)
circleView.backgroundColor = [UIColor redColor];
return circleView;
}
...和alignCircleViews
方法:
- (void)alignCircleViews {
int numberOfSubviews = [self.containerView.subviews count];
CGFloat totalWidth = (numberOfSubviews * self.circleViewFrame.size.width) + (numberOfSubviews - 1) * self.delta;
CGFloat x = (self.containerView.frame.size.width/2) - (totalWidth/2);
for (int i = 0; i < numberOfSubviews; i++) {
UIView *circleView = self.containerView.subviews[i];
circleView.frame = CGRectMake(x,
self.circleViewFrame.origin.y,
self.circleViewFrame.size.width,
self.circleViewFrame.size.height);
x += self.circleViewFrame.size.width + self.delta;
}
}
这是最重要的方法,它会在每次添加新的circleView时自动重新对齐所有子视图。其结果将是这样的:
简单的步骤:追加圈容器视图,调整大小容器视图,居中对齐容器视图
-(void)addToContanerView:(CircleView*)circle{ circle.rect.frame = CGrectMake(containers_end,container_y,no_change,no_change); [containerView addSubview:circle]; [containerView sizeToFit]; containerView.center = self.view.center; }
假设: containers_end & containers_y可以从CGRectMax函数获取, for UIView SizeToFit方法检查here
为了照顾轮换使用,请确保您的Autoresizing子视图设置为左侧,右侧底部和顶部边距。
您可以尝试使用此库。我已经在我的几个项目中使用过它,到目前为止,它工作得非常好。
试过'layoutSubviews'或自动布局约束? – Wain
你在使用哪种自动布局或自动调整掩码? – Lance
我有限制启用,但我发现他们非常反直觉相比,以及我用过的其他技术哈哈。我希望有人能建议最好的办法做到这一点,因为我从字面上不知道从哪里开始...... – Chris