iOS:UIButton titleLabel – 它什么都做?
我想做一个types为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方法不被弃用 – 它应该工作。
我已经遇到过这几次,总是只是解决它,但我真的很想弄明白。 有任何想法吗?
像这样设置titleLabel
的text
属性不起作用。 相反,调用-setTitle:forState:
在button上:
[editButton setTitle:@"Edit" forState:UIControlStateNormal]
这是因为这个button对于不同的状态可以有不同的标题(例如, UIControlStateDisabled
, UIControlStateHighlighted
)。 如果您没有明确指定其他属性,则为UIControlStateNormal
控件状态设置属性将应用于所有状态。
根据UIButton
的文档:
该类提供了设置button的标题,图像和其他外观属性的方法。 通过使用这些访问器,您可以为每个button状态指定不同的外观。
您可以根据状态自定义标签的颜色和阴影颜色。 请分别参阅-setTitleColor:forState
和-setTitleShadowColor:forState
。 titleLabel
上其余的属性,比如textAlignment
和font
,应该像你现在设置的那样工作,并且应该适用于所有的控制状态。
具体来说,请参阅UIButton
的titleLabel
属性的文档: https : //developer.apple.com/documentation/uikit/uibutton/1623992-titlelabel
titleLabel
本身是只读的,但这并不意味着你不能改变自己的属性的值,比如字体,换行符等等。