要在 iOS 中使用 UIButton 设置富文本并设置不同的颜色,你可以使用 NSAttributedString 来实现。下面是一个使用 Objective-C 代码设置不同颜色的 UIButton 的示例:

// 创建一个 UIButton
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(100, 100, 200, 50);

// 设置按钮的标题
NSString *buttonTitle = 'Hello World';
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:buttonTitle attributes:@{NSForegroundColorAttributeName: [UIColor redColor]}];
[button setAttributedTitle:attributedString forState:UIControlStateNormal];

// 设置按钮的另一部分标题的颜色
NSString *buttonSubtitle = 'Subtitle';
NSAttributedString *subtitleAttributedString = [[NSAttributedString alloc] initWithString:buttonSubtitle attributes:@{NSForegroundColorAttributeName: [UIColor blueColor]}];
NSMutableAttributedString *mutableAttributedString = [[NSMutableAttributedString alloc] initWithAttributedString:attributedString];
[mutableAttributedString appendAttributedString:subtitleAttributedString];
[button setAttributedTitle:mutableAttributedString forState:UIControlStateNormal];

// 添加按钮到视图上
[self.view addSubview:button];

在上述代码中,我们首先创建了一个按钮,并设置了按钮的 frame。然后,我们创建了一个 NSAttributedString 对象,用于设置按钮的标题的颜色。接下来,我们使用 setAttributedTitle:forState: 方法将富文本标题设置给按钮。然后,我们创建了另一个 NSAttributedString 对象来设置按钮的另一部分标题的颜色,并使用 NSMutableAttributedString 将两个富文本标题合并在一起。最后,我们使用 setAttributedTitle:forState: 方法将合并后的富文本标题设置给按钮。

希望这可以帮助到你!

iOS UIButton 富文本设置不同颜色 - Objective-C 代码示例

原文地址: https://www.cveoy.top/t/topic/o7ZM 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录