gpt4 book ai didi

ios - 使用 NSMutableAttributedString 更改 NSString 的颜色和大小部分

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:46:31 24 4
gpt4 key购买 nike

浏览了一些 NSAttributedString 示例,但似乎无法正常工作。我正在尝试更改 NSMutableAttributedString 的一部分的 sizecolor

我试过几个变体:

NSMutableAttributedString *hintText = [[NSMutableAttributedString alloc] initWithString:@"This is red and huge and this is not"];

//Black and large
[hintText setAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Futura-Medium" size:20.0f], NSForegroundColorAttributeName:[UIColor blackColor]} range:NSMakeRange(0, 11)];

//Rest of text -- just futura
[hintText setAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Futura-Medium" size:16.0f]} range:NSMakeRange(12, ((hintText.length -1) - 12))];

这只是改变文本的大小,而不是颜色。有人可以指出我正确的方向吗?

编辑:我这样使用:myUILabel.attributedText = hintText;

最佳答案

当我尝试做这样的事情时,我发现构建单独的部分(每个部分都是一个 NSAttributedString)然后用类似以下:

NSAttributedString *string1 = // Get the red and large string here
NSAttributedString *string2 = // Get the just futura string here

NSMutableAttributedString *hintText = [[NSMutableAttributedString alloc] init];
[hintText appendAttributedString:string1];
[hintText appendAttributedString:string2];

我发现这使得遵循逻辑流程变得更加容易,而且我从未发现这种方式具有需要优化的性能限制。


更新:

FWIW,我相信 OP 希望我使用以下代码工作:

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSMutableAttributedString *hintText = [[NSMutableAttributedString alloc] initWithString:@"This is red and huge and this is not"];

//Red and large
[hintText setAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Futura-Medium" size:20.0f], NSForegroundColorAttributeName:[UIColor redColor]} range:NSMakeRange(0, 20)];

//Rest of text -- just futura
[hintText setAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Futura-Medium" size:16.0f]} range:NSMakeRange(20, hintText.length - 20)];

[self.button setAttributedTitle:hintText forState:UIControlStateNormal];

}

请注意,他正在指定 [UIColor blackColor],我将其更新为 [UIColor redColor]。此外,我更新了范围计算以包括“This is red and huge”中的所有字符。

关于ios - 使用 NSMutableAttributedString 更改 NSString 的颜色和大小部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22360430/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com