2014-05-18 25 views
0

我想從NSString創建UIButton。 我有這樣一個字符串@「第一個按鈕」我想先獲取寬度像素的大小,並在創建一個按鈕後根據這個字符串,但我不知道它。如何從標題字符串創建按鈕

請指導我。

+0

可能重複來獲取文本的大小[如何獲得NSString的大小](http://stackoverflow.com/questions/2669063/how-to-get-the-size-of-a-nsstring) –

+0

@Lucas這不是最好的重複,因爲答案使用了現在已棄用的方法。 – rmaddy

+0

@rmaddy這很好,我們來參考一下。 http://stackoverflow.com/a/18897897/426959 –

回答

2

可以使用sizeWithAttributes得到NSStringCGSize(我們使用之前sizeWithFont但現在已經過時,法iOS 7),然後根據大小有如

NSString *string = @"First Button"; 

CGSize size = [string sizeWithAttributes: 
       @{NSFontAttributeName: 
        [UIFont systemFontOfSize:27.0f]}]; 
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 
button.frame = CGRectMake(0, 50, size.width, size.height); 
button.titleLabel.textColor = [UIColor blackColor]; 
[button setTitle:string forState:UIControlStateNormal]; 
button.backgroundColor = [UIColor redColor]; 
[self.view addSubview:button]; 

審查這方面的工作對我罰款創造UIButton。 希望這會幫助你。

+0

你遺漏了在問題中被問到的重要部分 - 如何確定字符串大小。 – rmaddy

+0

是的,你可以使用sizeWithAttributes審查更新的答案 – Buntylm

+0

我的朋友這個方法爲ios6工作? – user3599133

1

首先,你必須使用

NSString someText = @"some Text"; 
CGSize constraintSize = CGSizeMake(youMaxWidthForButton, youMaxHeightForButton); 
CGRect labelSize = [someText boundingRectWithSize:constraintSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont  systemFontOfSize:17.0f]} context:nil]; 

比你創建你UIButton

UIButton *button = [[UIButton alloc]initWithFrame:labelSize]; 

最後你設置按鈕標題的

button.titleLabel.text = someText; 
+0

我的朋友約束是什麼? – user3599133

+0

這是寬度和高度的最大值。例如,你不想讓你的按鈕比縱向模式下的iPhone寬度更大,那麼你可以使用'320'作爲最大寬度 – Argent