我使用以编程方式制作的按钮构建水平滚动视图(请参阅下面的代码)。现在我想在我通常使用自动布局的按钮之间留出一些间距。
int x = 0;
for (int i = 0; i < 14; i++) {
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(x, 0, 10, self.soundBar.frame.size.height)];
[button setTitle:[NSString stringWithFormat:@"Button %d", i] forState:UIControlStateNormal];
[button setBackgroundColor:[UIColor redColor]];
[button sizeToFit];
[[self soundBar] addSubview:button];
x += button.frame.size.width;
}
[[self soundBar] setContentSize:CGSizeMake(x, self.soundBar.frame.size.height)];
如何在这些按钮之间留下间距。我使用正确的方法来做到这一点吗?
答案 0 :(得分:0)
您可以根据数据获取字符串大小,并为该字符串添加填充以获得间距。
int x=0;
for (int i=0; i<14; i++)
{
UIButton *btn=[[UIButton alloc]init];
btn.titleLabel.font = [UIFont fontWithName:@"yourfontname" size:15];
[btn setTitle:[NSString stringWithFormat:@"Button %d", i] forState:UIControlStateNormal];
CGSize stringsize = [btn.title sizeWithFont:[UIFont fontWithName:@"yourfontname" size:15]];
btn.tag = i;
[btn setFrame:CGRectMake(x,0,stringsize.width+30, 45)];
x = x + stringsize.width + 30;
[self.scrollView addSubview:btn];
}
替换sizeWithFont
:
CGSize size = [string sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:15.0f]}];