您需要为正确显示定义按钮的大小,不幸的是,如果没有按钮的大小,您将无法实现您想要的,因为系统如何知道您想要显示的按钮大小......?
- (void)viewDidLoad
{
[super viewDidLoad];
Float32 _spaceBetweenButtons = 8.f;
Float32 _offsetY = 32.f;
Float32 _buttonWidth = 300.f; // width fo button
Float32 _buttonHeight = 32.f; // height of the button
for (int i = 0 ; i < 9 ; i++) {
UIButton *_myButton = [[UIButton alloc] initWithFrame:CGRectMake(0.f, 0.f, _buttonWidth, _buttonHeight)];
[_myButton setBackgroundColor:[UIColor blackColor]];
[_myButton setTitle:[NSString stringWithFormat:@"button #%d", i] forState:UIControlStateNormal]; // just add some text as title
[self.view addSubview:_myButton];
[_mybutton setCenter:CGPointMake(self.view.frame.size.width / 2.f, _offsetY + i * (myButton.frame.size.height + _spaceBetweenButtons))];
}
}
如果你想动态计算按钮的大小并且你想将按钮的高度与视图的高度对齐,这是一种方法:
NSInteger _numberOfButtons = 20;
Float32 _spaceBetweenButtons = 8.f;
Float32 _calculatedHeight = (self.view.frame.size.height - (_numberOfButtons + 1 * _spaceBetweenButtons)) / _numberOfButtons;
并且方法与上面相同,但我不确定在数百个按钮的情况下您是否会获得良好的 UI。:)