NSMutableAttributedString

NSMutableAttributedString

本文介绍了使用iOS 8中的NSMutableAttributedString对字符串的下划线部分无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我尝试在字符串的一部分下划线,例如' test string '字符串中的' string '部分。我正在使用 NSMutableAttributedString ,我的解决方案在 iOS7 上运行良好。I try to underline part of a string, for example, a 'string' part in 'test string' string. I'm using NSMutableAttributedString and my solution was working well on iOS7.NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"test string"];[attributedString addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:NSMakeRange(5, 6)];myLabel.attributedText = attributedString;问题是我的解决方案无法在 iOS8 了。花了一个小时测试 NSMutableAttributedString 的多个变种后,我发现这个解决方案只在范围从0开始时才有效(长度可以不同)。这是什么原因?我该如何解决这个问题?The problem is that my solution is not working in iOS8 anymore. After spending an hour on testing multiple variants of NSMutableAttributedString, I found out that this solution works only when range starts with 0 (length can differ). What is the reason for that? How can I workaround this?推荐答案 更新: 通过调查此问题:在iOS 8上显示NSMutableAttributedString 我终于找到了解决方案!Update:By investigating this question: Displaying NSMutableAttributedString on iOS 8 I finally found the solution! 你应该在字符串的开头添加NSUnderlineStyleNone。 Swift 4.0:Swift 4.0:let attributedString = NSMutableAttributedString()attributedString.append(NSAttributedString(string: "test ", attributes: [.underlineStyle: NSUnderlineStyle.styleNone.rawValue]))attributedString.append(NSAttributedString(string: "s", attributes: [.underlineStyle: NSUnderlineStyle.styleSingle.rawValue]))attributedString.append(NSAttributedString(string: "tring", attributes: [.underlineStyle: NSUnderlineStyle.styleNone.rawValue])) Objective-C:Objective-C: NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init]; [attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:@"test " attributes:@{NSUnderlineStyleAttributeName: @(NSUnderlineStyleNone)}]]; [attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:@"s" attributes:@{NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle), NSBackgroundColorAttributeName: [UIColor clearColor]}]]; [attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:@"tring"]];这种方法的另一个好处是没有任何范围。非常适合本地化的字符串。Another bonus of such approach is absence of any ranges. Very nice for localized strings.好像是Apple的bug :( Seems like it is Apple bug :( 这篇关于使用iOS 8中的NSMutableAttributedString对字符串的下划线部分无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-27 01:37