ios - 如何使用 NSAttributedString objective-c 为字符串的一部分加下划线

标签 ios objective-c nsattributedstring

仅当范围从零开始时,在字符串下方才有效。如果我从 1 开始,它就会工作。无论如何,绿色都有效。

+ (NSAttributedString*)returnNSAttributedString:(NSString*)string range:(NSRange)range WithColour:(UIColor*)colour WithUnderLine:(BOOL)underline {
    NSMutableAttributedString *attributedString =
    [[NSMutableAttributedString alloc] initWithString:string];
    if (underline) {
        [attributedString addAttributes:@{NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle)} range:range];
    }
    [attributedString addAttribute:NSForegroundColorAttributeName value:colour range:range];
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSRangeFromString(string)];
    return attributedString;
}

它适用于 iOS 7 而不是 iOS 8。

最佳答案

您可以使用 NSUnderlineStyleAttributeName 和 NSUnderlineColorAttributeName 属性。你可以像这样使用它:

NSRange foundRange = [wordString rangeOfString:@"Base Mix"];
if (foundRange.location != NSNotFound)
{
    [wordString beginEditing];
    [wordString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:1] range:foundRange];
    [wordString addAttribute:NSUnderlineColorAttributeName value:[NSColor redColor] range:foundRange];
    [wordString endEditing];
}

关于ios - 如何使用 NSAttributedString objective-c 为字符串的一部分加下划线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26423467/

相关文章:

ios - 将 attributedText 分配给 UILabel 会使应用程序崩溃并返回 'NSConcreteMutableAttributedString initWithString::nil value'

ios - 如何在iOS中使特定部分功能等待

ios - 如何使用 sharekit 在 Tumblr 上分享

ios - watchOS 通知可以显示自定义嵌入字体吗

iphone - 这个数据模型可以使用 NSBinaryStoreType 吗?

objective-c - 保存时检测 NSManagedObject 的更改

iphone - 将 UITableViewCell 连接到 Action

iphone - [[NSDate date] retain] 和 [[NSDate alloc] init] 的区别

ios - 更改字形中单个字符的颜色

iphone - 当 NSAttributedString + NSString 发送到 UIActivityViewController 并选择邮件应用程序时,iOS 7 应用程序崩溃