Wednesday, 15 April 2015

objective c - NSMutableAttributedString with NSRange issue -



objective c - NSMutableAttributedString with NSRange issue -

i have next string

22\nshaʻban\n1435

and i'm using nsmutableattributedstring format above string using multiple fonts follows:

nsstring* orgstring=@"22\nshaʻban\n1435"; nsmutableattributedstring *attstring=[[nsmutableattributedstring alloc] initwithstring:[datestr stringbytrimmingcharactersinset:[nscharacterset whitespacecharacterset]]]; uifont *dayfont=[uifont fontwithname:@"helvetica-bold" size:40.0f]; uifont *monthfont=[uifont fontwithname:@"arial" size:22.0f]; uifont *yearfont=[uifont fontwithname:@"arial" size:20.0f]; //format day part [attstring addattribute:nsfontattributename value:dayfont range:nsmakerange(0,2)]; //format month part [attstring addattribute:nsfontattributename value:monthfont range:nsmakerange(3,[self indexof:[datestr substringfromindex:3] andsearchchar:@"\n"])]; //format year part, app crashes here [attstring addattribute:nsfontattributename value:yearfont range:nsmakerange([self indexof:[datestr substringfromindex:3] andsearchchar:@"\n"]+1,[datestr length])]; - (int) indexof:(nsstring*)orgstr andsearchchar:(nsstring *)chartosearc { nsrange range = [orgstr rangeofstring:chartosearc]; if ( range.length > 0 ) { homecoming range.location; } else { homecoming -1; } }

i don't know why crashes when trying format lastly part, made arrange lastly position in part 2 +1 length of string, help please

i'd suggest this:

nsstring* orgstring=@"22\nshaʻban\n1435"; nsmutableattributedstring *attrstring = [[nsmutableattributedstring alloc] init]; uifont *dayfont = [uifont fontwithname:@"helvetica-bold" size:40.0f]; uifont *monthfont = [uifont fontwithname:@"arial" size:22.0f]; uifont *yearfont = [uifont fontwithname:@"arial" size:20.0f]; nsarray *array = [orgstring componentsseparatedbystring:@"\n"]; [attrstring appendattributedstring:[[nsattributedstring alloc] initwithstring:[array objectatindex:0] attributes:@{nsfontattributename: dayfont}]]; [attrstring appendattributedstring:[[nsattributedstring alloc] initwithstring:@"\n"]]; [attrstring appendattributedstring:[[nsattributedstring alloc] initwithstring:[array objectatindex:1] attributes:@{nsfontattributename: monthfont}]]; [attrstring appendattributedstring:[[nsattributedstring alloc] initwithstring:@"\n"]]; [attrstring appendattributedstring:[[nsattributedstring alloc] initwithstring:[array objectatindex:2] attributes:@{nsfontattributename: yearfont}]];

so, no nsrange issue. plus said @wain, misunderstood what's nsrange. instead of you're doing, 1 time found location, had put, sec parameter of nsmakerange: nextlocation-currentlocation. id est, lastly one, this:

nsmakerange([self indexof:[datestr substringfromindex:3] andsearchchar:@"\n"]+1, [datestr length]-[self indexof:[datestr substringfromindex:3] andsearchchar:@"\n"]+1)

objective-c cocoa-touch nsattributedstring nsrange

No comments:

Post a Comment