How to underline part of string with NSAttributedString objective-c

自闭症网瘾萝莉.ら 提交于 2019-12-10 17:39:58

问题


Underling a string only works when the range starts from zero. If i start it at 1 then it works. The green colour works regardless.

+ (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;
}

it works on iOS 7 not iOS 8.


回答1:


You can use the NSUnderlineStyleAttributeName and NSUnderlineColorAttributeName attributes. You can use it like this:

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:


Swift:

A little method. Gets a string and returns a NSMutableAttributedString with underline attribute over the full string-length.

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
}


来源:https://stackoverflow.com/questions/26423467/how-to-underline-part-of-string-with-nsattributedstring-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!