仅在范围从零开始时,仅对字符串进行支撑。如果我从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。
答案 0 :(得分:10)
您可以使用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];
}
答案 1 :(得分:1)
<强>夫特:强>
一个小方法。获取一个字符串,并返回一个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
}