我使用通过编程制作的按钮来构建水平滚动视图(请参见下面的代码)。现在我想在通常使用自动布局的按钮之间留出一些间距。
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)];
我如何才能在这些按钮之间留出间距。我是否使用正确的方法来做到这一点?
您可以根据数据获取字符串大小,并在该字符串中添加填充以保持间距。
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]}];
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句