2011-05-27 51 views
2

字幕我需要一個UIButton顯示文本,其中的第一個用作標題和第二爲某種字幕的兩行,所以它應該是一個較小的字體大小的。 現在我的按鈕有兩行,自定義字體,標題/副標題的內容分別來自UILabel標題和不同字體大小爲的UIButton

UIFont *displayFont = [UIFont fontWithName:@"Chalkboard" size:15]; 
NSString *buttonLabel; 
UILabel *headline = [[UILabel alloc] init]; 
headline.text = @"This is the title"; 
UILabel *subtitle = [[UILabel alloc] init]; 
subtitle.text = @"this is the sub"; 

buttonLabel = [NSString stringWithFormat:@"%@\n%@", headline.text, subtitle.text]; 
[openDetail.titleLabel setLineBreakMode:UILineBreakModeWordWrap]; 
[openDetail setTitle:buttonLabel forState:UIControlStateNormal]; 
[openDetail.titleLabel setTextAlignment:UITextAlignmentCenter]; 
openDetail.titleLabel.font = displayFont; 

我試圖將自己的標籤設置爲displayFont,這樣我就可以進行第二次UIFont,使得它的副標題。不幸的是,按鈕標籤不會是這種字體,如果我保留其餘的如上所示,但將切換回Arial,我認爲它是,並且根本沒有改變字體大小。

任何想法如何在第二行中實現更小的字體大小?

字體的側面問題:我將Chalkboard.ttc添加到我的資源中,並將其添加爲我的info.plist中的一個條目,作爲「應用程序提供的字體」。不過,如果我嘗試在IB中設置字體,則會顯示另一種字體(與Helvetica非常相似)。我是否真的必須現在以編程方式設置每個按鈕字體?

回答

5

試試這個

UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
[btn setFrame:CGRectMake(20 , 13, 200, 85)]; 
UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(8, 8, 185, 30)]; 
[title setBackgroundColor:[UIColor clearColor]]; 
[title setFont:[UIFont fontWithName:@"Chalkboard" size:14]]; 
[title setFont:[UIFont boldSystemFontOfSize:18]]; 
[email protected]"This is the title"; 
[title setTextColor:[UIColor blackColor]]; 
[btn addSubview:title]; 

UILabel *subtitle = [[UILabel alloc]initWithFrame:CGRectMake(8, 20, 185, 30)]; 
[subtitle setBackgroundColor:[UIColor clearColor]]; 
[subtitle setFont:[UIFont fontWithName:@"Helvetica" size:14]]; 
[email protected]"This is the sub"; 
[subtitle setTextColor:[UIColor blackColor]]; 
[btn addSubview:subtitle]; 

[title release]; 
[subtitle release]; 

[self.view addSubview:btn]; 
+0

我會做到這一點的方法是在其內部產生的UIButton的兩個的UILabel子類。所以,如果你需要重用這個按鈕,你不需要重寫所有的代碼。另外,你可以創建像setTitle:forState這樣的方法。 – 2011-05-27 10:57:31

+0

@Raphael Petegrosso我不知道如何繼承的UIButton,但似乎不僅僅是在按鈕的上方添加一個標籤一個清潔的解決方案(我做了什麼現在使用IB和UIFont)。我讀過的地方UIButton不應該被分類。你這樣做之前? – Nareille 2011-05-31 14:21:56

+0

是的,你可以繼承UIButton。我總是這樣做沒有問題。 – 2011-06-02 03:18:30

1

你的問題是,只有在你正在使用的系統按鈕的單個標籤。那隻能有一種字體。

如果你想要更復雜的按鈕,你必須自己構建它們。

你的一個選擇就是將你的字幕添加到現有的按鈕。這是一個簡單的例子。我假設你有一個叫做myButton的IB按鈕的插座。

UILabel *subTitle = [[[UILabel alloc] initWithFrame:CGRectMake(0, 20, 100, 30)] autorelease]; 
[subTitle setText:@"Subtitle"]; 
[subTitle setTextColor:[UIColor blackColor]]; 
[subTitle setBackgroundColor:[UIColor clearColor]]; 
[subTitle setFont:[UIFont fontWithName:@"American Typewriter" size:12]]; 

[myButton setTitle:@"Main title" forState:UIControlStateNormal]; 
[myButton addSubview:subTitle]; 

如果這是你在多個地方需要的東西,你應該把按鈕變成它自己的類,標題和副標題有很好的屬性。其實你應該這樣做。 :-)

相關問題