UIButton带有图像的标题起源在不同的iOS版本中确实有所不同。以下是一些解决方法,包括代码示例:
在iOS 7及更早的版本中,可以使用UIButton
的setImage:forState:
方法设置按钮的图像,使用setTitle:forState:
方法设置按钮的标题。
代码示例:
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *image = [UIImage imageNamed:@"button_image.png"];
[button setImage:image forState:UIControlStateNormal];
[button setTitle:@"Button Title" forState:UIControlStateNormal];
在iOS 8及更高的版本中,可以使用UIButton
的setImage:forState:
方法设置按钮的图像,并使用setAttributedTitle:forState:
方法设置按钮的富文本标题。
代码示例:
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *image = [UIImage imageNamed:@"button_image.png"];
[button setImage:image forState:UIControlStateNormal];
NSAttributedString *title = [[NSAttributedString alloc] initWithString:@"Button Title" attributes:@{NSForegroundColorAttributeName: [UIColor whiteColor]}];
[button setAttributedTitle:title forState:UIControlStateNormal];
请注意,富文本标题的设置方式可能会根据您的具体需求而有所不同。在上面的示例中,我们将标题文本设置为白色。
通过根据不同的iOS版本来选择使用适当的方法,您可以确保您的应用在各个iOS版本上都能正确显示UIButton带有图像的标题。