我正在尝试根据数组中的按钮数量将按钮居中。
因此,对于一个对象,您可以通过以下方式将其居中:
CGRect originalFrame = self.view.frame;
button.frame = CGRectMake(orignalFrame.size.width/2 - self.button.frame.size.width/2, etc, etc, etc);
但是,当数组中有 n 个对象时,我很难将它们居中。这是我到目前为止所拥有的,但它从未对齐 x:
-(void)displayIconsFromSignedInArray:(NSArray *)array {
CGFloat buttonWidthHeight = 50;
CGFloat x = (self.view.frame.size.width / array.count) - (buttonWidthHeight / 2)*array.count;
for (UIButton *button in array) {
button.frame = CGRectMake(x, self.view.frame.size.height/2 - buttonWidthHeight/2, buttonWidthHeight, buttonWidthHeight);
x += buttonWidthHeight + 2.5;
[self.view addSubview:button];
}
}
这就是我最终得到的结果:
从外观上看,FB 图标的原点从宽度的一半开始,但我无法正确理解。请帮助我理解这样做的过程,要么是更好的方法,要么是修复这种方法。谢谢。
最佳答案
第一个偏移量 = 一半宽度 - 所有按钮宽度的一半。可能需要考虑view不能连续显示button的情况。
CGFloat x = self.view.frame.size.width/2 - buttonWidthHeight*array.count/2;
关于ios - 基于数组中的 n 个图像在 View 中居中图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31496858/