2011-05-27 59 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]; 

如果这是你在多个地方需要的东西,你应该把按钮变成它自己的类,标题和副标题有很好的属性。其实你应该这样做。 :-)