2012-03-05 34 views
3

我已經實現了一個自定義按鈕,如下所示。如何在iPhone中根據它調整自定義按鈕的大小文字

UIButton *mainBtn = [UIButton buttonWithType:UIButtonTypeCustom]; 
[mainBtn setTitle:@"Meeting" forState:UIControlStateNormal]; 
[mainBtn setFrame:CGRectMake(80, 7, 72, 35)]; 
[mainBtn setBackgroundImage:[UIImage imageNamed:@"buttonActive.png"] forState:UIControlStateNormal]; 
mainBtn.contentEdgeInsets = UIEdgeInsetsMake(18, 5, 18, 10); 
[mainBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; 

這裏按鈕標題將是動態的。所以現在我需要根據標題dynamicaly的長度來改變按鈕的寬度。 CGRectMake與給定的寬度不會工作。有人能幫我做到嗎?

+0

這應該是訣竅... http://stackoverflow.com/a/4978003/716216 – 2012-03-05 11:05:02

回答

6

只需使用下面的代碼,

CGSize expectedLabelSize = [mainBtn.titleLabel.text sizeWithFont:mainBtn.titleLabel.font]; 
mainBtn.frame = CGRectMake(x, y, expectedLabelSize.width+10, expectedLabelSize.height); 
0

甲simpel解決方案將是[mainBtn sizeToFit]; 但我不知道這是否考慮到了您的edgeInsets。

相關問題