你可以使用一個UICollectionView
要做到這一點,但它並不難只是使用的UIButtons
的陣列來實現。您可以使用sizeToFit
來根據其標題獲取按鈕大小。要讓你的按鈕環繞,你應該檢查它是否會超過你添加的視圖的最大值x,在你的情況下是self.view
。
例如,你可以這樣說:
- (void)viewDidLoad {
[super viewDidLoad];
NSArray *buttonStrings = @[@"how", @"now", @"brown", @"cow", @"the", @"quick", @"brown", @"fox"];
NSMutableArray *buttons = [[NSMutableArray alloc]initWithCapacity:[buttonStrings count]];
for (NSString *string in buttonStrings)
{
UIButton *button = [self buttonForString:string];
[buttons addObject:button];
}
[self layoutButtonArray:buttons inView: self.view];
}
// takes an array of buttons and adds them as subviews of view
- (void)layoutButtonArray:(NSArray<UIButton *> *)buttons inView:(UIView *)view
{
CGFloat spacing = 10.0;
CGFloat xOffset = spacing;
CGFloat yOffset = spacing;
for (UIButton *button in buttons)
{
if((xOffset + button.bounds.size.width + spacing) > CGRectGetMaxX(view.bounds))
{
xOffset = spacing;
yOffset += (button.bounds.size.height + spacing);
}
button.frame = CGRectMake(xOffset, yOffset, button.bounds.size.width, button.bounds.size.height);
[view addSubview:button];
xOffset += (button.bounds.size.width + spacing);
}
}
// Takes a string returns a button sized to fit
- (UIButton *) buttonForString:(NSString *)string
{
UIButton *button = [[UIButton alloc]initWithFrame:CGRectZero];
button.backgroundColor = [UIColor redColor];
[button setTitle:string forState:UIControlStateNormal];
[button sizeToFit];
// if you want to have a minimum width you can add that here
button.frame = CGRectMake(button.frame.origin.x, button.frame.origin.y, MAX(button.frame.size.width, kMinWidth), button.frame.size.height);
return button;
}
是你正在尋找一個「的網格按鈕」搜索。 – vikingosegundo