简体   繁体   中英

Getting crash while adding attributes to NSMutableAttributedString for a particular range in iOS

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]
                                                initWithString:@"I have read, understand and agree to the following terms and conditions and web usage policy." attributes:nil];
NSRange conditionlinkRange = NSMakeRange(50,70);
// for the word "terms and conditions" in the string above
NSRange policylinkRange = NSMakeRange(75,92);
NSDictionary *linkAttributes = @{ NSForegroundColorAttributeName : [UIColor colorWithRed:0.05 green:0.4 blue:0.65 alpha:1.0],
                                  NSUnderlineStyleAttributeName : @(NSUnderlineStyleSingle) };
[attributedString addAttributes:linkAttributes range:policylinkRange];
[attributedString addAttributes:linkAttributes range:conditionlinkRange];

Application gets crashed at this line [attributedString addAttributes:linkAttributes range:policylinkRange];

Try This

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"I have read, understand and agree to the following terms and conditions and web usage policy." attributes:nil];

NSRange conditionlinkRange = NSMakeRange(51,20);
NSRange policylinkRange = NSMakeRange(86,6);
NSDictionary *linkAttributes = @{ NSForegroundColorAttributeName : [UIColor colorWithRed:0.05 green:0.4 blue:0.65 alpha:1.0], NSUnderlineStyleAttributeName : @(NSUnderlineStyleSingle) };

[attributedString addAttributes:linkAttributes range:policylinkRange];
[attributedString addAttributes:linkAttributes range:conditionlinkRange];

Use this:

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"I have read, understand and agree to the following terms and conditions and web usage policy." attributes:nil];
    NSRange conditionlinkRange = [attributedString.string rangeOfString:@"terms and conditions"];

    // for the word "terms and conditions" in the string above
    NSRange policylinkRange = [attributedString.string rangeOfString:@"policy"];
    NSDictionary *linkAttributes = @{ NSForegroundColorAttributeName : [UIColor colorWithRed:0.05 green:0.4 blue:0.65 alpha:1.0],  NSUnderlineStyleAttributeName : @(NSUnderlineStyleSingle) };

    [attributedString addAttributes:linkAttributes range:policylinkRange];
    [attributedString addAttributes:linkAttributes range:conditionlinkRange];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM