我想要创建一个UIButton,并设置其类型为UIButtonTypeCustom(以适配样式)。我想通过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方法没有过时--它应该可以工作。
我之前遇到这个问题好几次了,总是绕开它解决,但我真的很想找出解决方法。有什么想法吗?
text
属性只是调用-setTitle:forState
的捷径,但实际上并不是这样。 - CIFiltertitleLabel.textAlignment
不正确。要对齐文本,您必须使用titleLabel.contentHorizontalAlignment = .Left
。 - Phil Andrews