gpt4 book ai didi

ios - 多行 UILabel 上的 NSAttributedString 切断第一行

转载 作者:可可西里 更新时间:2023-11-01 03:58:12 27 4
gpt4 key购买 nike

我已经查看了大约 10 个关于 SO 的问题,但仍然做不到。

我有一个多行 UILabel(在 Interface Builder 中创建,numberOfLines 设置为 0)通常呈现如下:

enter image description here

我想强调“服务条款”和“隐私政策”,所以我添加了这段代码:

NSString *text = self.agreement.text;
NSMutableAttributedString *aString = [[NSMutableAttributedString alloc] initWithString:text];

NSRange privacyRange = [text rangeOfString:@"privacy policy" options:NSCaseInsensitiveSearch];
[aString addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:privacyRange];

NSRange tosRange = [text rangeOfString:@"terms of service" options:NSCaseInsensitiveSearch];
[aString addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:tosRange];

self.agreement.attributedText = aString;

但是结果是这样的:

enter image description here

我需要做什么才能显示两条线,并在适当的范围下划线?

此外,我不希望使用 OHAttributedLabel 或 TTTAttributedLabel 之类的第 3 方库,因为这是我的应用中唯一需要在一段文本上加下划线的地方。

我尝试过的

  • 设置属性文本后调用sizeToFit
  • 改为使用 UITextView。两条线都正确呈现,但我失去了中心对齐。
  • 重置代码中的numberOfLineslineBreakMode

Sascha 要求我上传两张屏幕截图,其中背景颜色设置为不清晰。奇怪的是,一切都如预期般出现!不确定如何理解这个或它告诉我们什么。

enter image description here

最佳答案

  1. 首先像您一样创建属性文本:

    NSString *text = self.agreement.text;
    NSMutableAttributedString *aString = [[NSMutableAttributedString alloc] initWithString:text];

    NSRange privacyRange = [text rangeOfString:@"privacy policy" options:NSCaseInsensitiveSearch];
    [aString addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:privacyRange];

    NSRange tosRange = [text rangeOfString:@"terms of service" options:NSCaseInsensitiveSearch];
    [aString addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:tosRange];
  2. 将您想使用的字体分配给属性字符串:

    [aString addAttribute:NSFontAttributeName value:self.agreement.font range:(NSRange){0, aString.length}];

    self.agreement.attributedText = aString;
  3. 将您的标签定义为多行:

    self.agreement.numberOfLines = 0;
    self.agreement.lineBreakMode = NSLineBreakByWordWrapping;
  4. 估计您的标签尺寸:

    CGRect myLabelRect = [aString boundingRectWithSize:CGSizeMake(self.view.frame.size.width, INT_MAX)
    options:NSStringDrawingUsesLineFragmentOrigin
    context:nil];
  5. 添加要查看的标签时使用估计大小:

    self.agreement.frame = CGRectMake(self.view.frame.size.width / 2 - myLabelRect.size.width / 2,
    0,
    myLabelRect.size.width,
    myLabelRect.size.height);
    [self.view addSubview:self.agreement];

关于ios - 多行 UILabel 上的 NSAttributedString 切断第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22237886/

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