【问题标题】:How to underline part of string with NSAttributedString objective-c如何使用 NSAttributedString objective-c 为字符串的一部分加下划线
【发布时间】:2014-10-17 10:53:34
【问题描述】:
仅当范围从零开始时,在字符串下添加才有效。如果我从 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。
【问题讨论】:
标签:
ios
objective-c
nsattributedstring
【解决方案1】:
您可以使用 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];
}
【解决方案2】:
斯威夫特:
一个小方法。获取一个字符串并返回一个带有下划线属性的 NSMutableAttributedString 超过整个字符串长度。
func getUnderlinedAttributedString(string string: String) -> NSMutableAttributedString
{
let attributedString = NSMutableAttributedString.init(string: string)
let stringRange = NSMakeRange(0, attributedString.length)
attributedString.beginEditing()
attributedString.addAttribute(NSUnderlineStyleAttributeName, value: 1, range: stringRange)
attributedString.endEditing()
return attributedString
}