Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/95.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
iOS水平滚动视图,带有使用自动布局的按钮_Ios - Fatal编程技术网

iOS水平滚动视图,带有使用自动布局的按钮

iOS水平滚动视图,带有使用自动布局的按钮,ios,Ios,我正在构建一个带有按钮的水平滚动视图,这些按钮是通过编程实现的(请参见下面的代码)。现在,我希望在我通常使用的自动布局中,按钮之间有一些间距 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 se

我正在构建一个带有按钮的水平滚动视图,这些按钮是通过编程实现的(请参见下面的代码)。现在,我希望在我通常使用的自动布局中,按钮之间有一些间距

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)];
intx=0;
对于(int i=0;i<14;i++){
UIButton*button=[[UIButton alloc]initWithFrame:CGRectMake(x,0,10,self.soundBar.frame.size.height)];
[按钮设置标题:[NSString stringWithFormat:@“按钮%d”,i]用于状态:UIControlStateNormal];
[按钮设置背景颜色:[UIColor REDCLOR]];
[button sizeToFit];
[[self soundBar]添加子视图:按钮];
x+=按钮.框架.尺寸.宽度;
}
[[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];
}

看起来不错,有什么问题吗?我个人可能会以编程方式添加自动布局约束。问题是我无法获得我的专利按钮权限?@KevinRietveld为字符串长度和填充间距添加了一个答案,由于不推荐使用的函数,更改某些代码时需要使用非常好的填充方式。@KevinRietveld yes
sizeWithFont
不推荐使用你必须使用其他方法。我正在更新答案。如果这对你有帮助的话,你可以像这样接受答案
CGSize size = [string sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:15.0f]}];