我试着在字符串的某个部分下面画线,例如,test string字符串中的string部分.我使用NSMutableAttributedString,我的解决方案在iOS7上运行良好.

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]
        initWithString:@"test string"];
[attributedString addAttribute:NSUnderlineStyleAttributeName
                         value:@(NSUnderlineStyleSingle)
                         range:NSMakeRange(5, 6)];
myLabel.attributedText = attributedString;

问题是我的解决方案不再适用于iOS8.在花了一个小时测试了NSMutableAttributedString的多个变体之后,我发现这个解决方案只有在范围从0开始时才有效(长度可以不同).原因是什么?我该如何解决这个问题?

推荐答案

Update:

You should add NSUnderlineStyleNone at the beginning of the string.

Swift 4.2(删除none个):

let attributedString = NSMutableAttributedString()
attributedString.append(NSAttributedString(string: "test ",
                                           attributes: [.underlineStyle: 0]))
attributedString.append(NSAttributedString(string: "s",
                                           attributes: [.underlineStyle: NSUnderlineStyle.single.rawValue]))
attributedString.append(NSAttributedString(string: "tring",
                                           attributes: [.underlineStyle: 0]))

目标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"]];

这种方法的另一个好处是没有任何范围.非常适合本地化字符串.

似乎是苹果病毒:(

Objective-c相关问答推荐

Objective-C NSMutableArray 在枚举时发生了变异?

TWTweetComposeViewController 在 IOS6 中已弃用

'if not' 的 Objective-C 预处理器指令

将 Objective-C 指针类型NSString *转换为 C 指针类型CFStringRef(又名const struct __CFString *)需要桥接转换

如何创建 NSIndexPath:indexPathWithIndexes:length 所需的索引:

获取按其各自值排序的 NSDictionary 键

iOS 编译错误:CDVCommandDelegateImpl没有可见的@interface 声明 Select 器执行:

如何在 UICollectionView 中居中行?

获取对 UIApplication 委托的引用

isEqualTo: 和 isEqual 之间的区别:

Xcode:可以为协议接口所需的方法自动创建存根吗?

如何切换回已经加载的 UIViewController?

检测代码是否在 Objective-C 的主线程上运行的正确方法是什么? (iOS)

如何从 CGPoint 和 CGSize 创建 CGRect?

我应该使用 NSUserDefaults 还是 plist 来存储数据?

如何以编程方式在 UINavigationController 中按下返回按钮

如何让 UITextView 检测网站、邮件和电话号码的链接

更改导航栏的字体

Foo 类在 MyApp 和 MyAppTestCase 中都实现了.将使用两者之一.哪个是未定义的

按字典中键的值对字典的 NSArray 进行排序