2011-02-05 37 views
27

我想创建一个类型为UIButtonTypeCustom的UIButton(用于形状)。我想使用button.titleLabel来指定标题,因为我需要指定字体。下面的代码看起来应该可以工作,但不会 - 没有标签显示,句点。iOS:UIButton titleLabel - 它什么都做?

UIImage *editButtonImage = [UIImage imageNamed: @"editButton.png"]; 
float width = editButtonImage.size.width; 
float height = editButtonImage.size.height; 

UIButton *editButton = [UIButton buttonWithType: UIButtonTypeCustom]; 
editButton.frame = CGRectMake(0, 0, width, height); 
[editButton setBackgroundImage: editButtonImage forState: UIControlStateNormal]; 
editButton.adjustsImageWhenHighlighted = YES; 
editButton.titleLabel.text = @"Edit"; 
editButton.titleLabel.textColor = [UIColor whiteColor]; 
editButton.titleLabel.textAlignment = UITextAlignmentCenter; 
editButton.titleLabel.font = [UIFont fontWithName: @"Helvetica" size: 14]; 
[self.view addSubview: editButton]; 

大家总是说要使用setTitle:forState:但是这会给你一个我不喜欢的字体。 titleLabel方法不被弃用 - 它应该起作用。

我已经遇到过这几次,总是只是解决它,但我真的很想弄明白。有任何想法吗?

回答

79

设置titleLabeltext这样的属性没有效果。相反,调用-setTitle:forState:按钮:

[editButton setTitle:@"Edit" forState:UIControlStateNormal] 

这样做的原因是因为该按钮可以有不同的状态(例如,UIControlStateDisabledUIControlStateHighlighted)不同的称呼。如果您没有明确指定其他属性,则为UIControlStateNormal控制状态设置属性将应用于所有状态。

每的文档UIButton

此类提供用于设置标题,图像和按钮的其它外观性质的方法。通过使用这些访问器,您可以为每个按钮状态指定不同的外观。

您可以根据状态自定义标签的颜色和阴影颜色。分别见-setTitleColor:forState-setTitleShadowColor:forStatetitleLabel上的其他属性(如textAlignmentfont)应该按照您现在设置的那样工作,并应适用于所有控制状态。

具体来说,请参阅文档UIButtontitleLabel属性:https://developer.apple.com/documentation/uikit/uibutton/1623992-titlelabel

titleLabel本身是只读的,但是,这并不意味着你不能改变它自己的属性值,如字体,换行符模式等。

+1

所以,你不能使用titleLabel设置的东西是实际的文本值。这对我来说似乎有点奇怪,但没关系。 – Amagrammer 2011-02-05 23:59:15