突出显示或下划线字符串中的特定单词

时间:2014-01-28 05:12:13

标签: ios objective-c nsmutableattributedstring

我想强调或强调NSString中的一组特定字词。我能够检测到这些单词是否存在,我只是无法突出显示它们。

NSString * wordString = [NSString stringWithFormat:@"%@", [self.myArray componentsJoinedByString:@"\n"]];

self.myLabel.text = wordString;

if ([wordString rangeOfString:@"Base Mix"].location == NSNotFound)
{
    NSLog(@"string does not contain base mix");
}
else
{
    NSLog(@"string contains base mix!");

    NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:wordString];

    NSString * editedString = [NSString stringWithFormat:@"%lu", (unsigned long)[wordString rangeOfString:@"Base Mix"].location];

    NSRange theRange = NSMakeRange(0, [editedString length]);

    [string beginEditing];
    [string removeAttribute:NSForegroundColorAttributeName range:theRange];
    [string addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:theRange];
    [string endEditing];

    [self.myLabel setAttributedText:string];
}

此代码更接近正确的路径。我确实看到一个突出显示的字符,但它是字符串中的第一个字符,而不是我搜索过的字符。

5 个答案:

答案 0 :(得分:5)

您可以使用NSUnderlineStyleAttributeNameNSUnderlineColorAttributeName属性。我想你可以像这样使用它:

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 :(得分:2)

您可以使用以下与NSAttributed字符串相关的代码。仅适用于ios6 +

NSString *tem = @"String with base Mix dfsdfsd ";
 NSString *substring = @"base Mix";
 NSRange range;
 if ((range =[tem rangeOfString:substring]).location == NSNotFound)
 {
       NSLog(@"string does not contain base mix");
 }
 else
 {
       NSMutableAttributedString *temString=[[NSMutableAttributedString alloc]initWithString:tem];
       [temString addAttribute:NSUnderlineStyleAttributeName
                                  value:[NSNumber numberWithInt:1]
                                  range:(NSRange){range.location,substring.length}];
        NSLog(@"%@",temString);
       self.yourLabel.attributedText = temString;
 }     

答案 2 :(得分:0)

我认为NSAttributedString缺少该部分。您可以尝试使用Three20

答案 3 :(得分:0)

在@ user1118321的答案的帮助下我写了这个函数,我会节省一些时间

func highlightedString(allText:String,toBeHighlighted word:String) -> NSAttributedString{

        var putInString = NSMutableAttributedString.init()
        var giveFrom = NSMutableString.init(string: allText)

        while true {
            let range = giveFrom.range(of: word)
            let index = range.location + range.length
            if range.location == NSNotFound{
                putInString.append(NSAttributedString.init(string: giveFrom as String))
                break
            }
            else{
                let slite = giveFrom.substring(to: index)
                let highlightedSlite = NSMutableAttributedString.init(string: slite)
                highlightedSlite.addAttributes([NSAttributedStringKey.backgroundColor : UIColor.yellow], range: range)
                giveFrom = giveFrom.substring(from: index) as! NSMutableString
                putInString.append(highlightedSlite)
            }
        }
        return putInString
    }

可能代码不是很清楚,所以我欢迎任何编辑都有帮助

突出显示许多字词

func higlighted(allText:String,words:[String]) ->NSAttributedString{

        let allAttributedText = NSMutableAttributedString.init(string: allText)
        var ranges = [NSRange]()

        for word in words{
            var string = allAttributedText.string as NSString
            var i = 0
            while true {
                var range = string.range(of: word)
                if range.location == NSNotFound {
                    break
                }
                i = i + range.location + word.count
                string = string.substring(from: range.location + range.length) as NSString
                range.location = i - word.count
                print("\(range)  XX \(word)" )

                ranges.append(range)
            }
        }
        for range in ranges{
            allAttributedText.addAttributes([NSAttributedStringKey.backgroundColor : UIColor.yellow], range: range)
        }
        return allAttributedText
    }

答案 4 :(得分:0)

您可以像这样创建NSString类的类别方法

-(NSMutableAttributedString*)addAttributesToWords:(NSString*)string attributes:(NSArray*)attributes {
    NSRange range;
    if ((range = [self rangeOfString:string]).location == NSNotFound){
        return [[NSMutableAttributedString alloc] initWithString:self];
    }
    else{
        NSMutableAttributedString *result = [[NSMutableAttributedString alloc] initWithString:self];
        for (NSDictionary *attribute in attributes) {
            [result addAttributes:attribute range:range];
        }
        return result;
    }
}

使用方法:

NSArray *attributes = @[@{NSFontAttributeName : kFont_OpenSansSemiBold14},
                        @{NSForegroundColorAttributeName : [UIColor darkGrayColor]}];

self.label.attributedText = [@"Hello There, this is a Test" addAttributesToWords:@"Hello There" attributes:attributes];
相关问题