27

我想制作一个 UIButtonTypeCustom 类型的 UIButton(用于形状)。我想使用 button.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 方法——它应该可以工作。

我之前遇到过几次并且总是解决它,但我真的很想弄清楚。有任何想法吗?

4

2 回答 2

79

像这样设置titleLabel'text属性没有效果。相反,调用-setTitle:forState:按钮:

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

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

根据以下文档UIButton

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

您可以根据状态自定义标签的颜色和阴影颜色。分别参见-setTitleColor:forState-setTitleShadowColor:forState。上的其余属性titleLabel,例如textAlignmentfont,应该按照您现在设置的方式工作,并且应该适用于所有控件状态。

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

titleLabel本身是只读的,但这并不意味着您不能更改其自身属性的值,例如字体、换行模式等。

于 2011-02-05T23:50:45.133 回答
0

以下是我使用 Swift 4.2 的方法。

counterButton.setTitle("Start Counter",
                      for:UIControl.State.normal)
于 2018-12-05T02:02:23.463 回答