2015-06-13 186 views
0

Im建立一個水平滾動視圖與程序化編程的按鈕(見下面的代碼)。現在我想在通常使用自動佈局的按鈕之間有一些間距。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 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

看起來沒問題,有什麼問題?個人可能會以編程方式添加自動佈局約束。 – Woodstock

+0

問題是,我無法達到我的專利按鈕權利? – KevinKevin

+0

@KevinRietveld爲字符串長度和填充添加了空格的答案 –

回答

0

您可以根據您的數據獲取字符串大小,並將間距添加到該字符串中。的sizeWithFont

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]; 
} 

更換:

CGSize size = [string sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:15.0f]}]; 
+0

非常感謝您爲改變某些代碼而需要的功能,因爲已棄用的函數。 – KevinKevin

+0

@KevinRietveld yes'sizeWithFont'已棄用,您必須使用其他方法。我正在更新答案。如果它對你有幫助,只要接受像http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work –