Anoop Vaidya
Anoop Vaidya

Reputation: 46533

Select Bold and Italicized text from textField

How can I select only bold and italicized text entered by user in a textField/textView ?

We can make a selected text bold, italicized, underline and any combination of these three but what about its vice-versa.

*This is not specific to Mac OSX or iOS, solution in either one is good for me.

EDIT:

I tried by reading the text in attributed string as :

NSAttributedString *string=self.textView.string;

But as textView and textField returns NSString so all formatting is gone.

Upvotes: 3

Views: 6373

Answers (1)

Daij-Djan
Daij-Djan

Reputation: 50089

on iOS use attributedText properties with labels/textfields

on OSX use attributedStringValue

you can then enumerate through the attributedText's attributes and check each attribute. Ill whip up some code (osx & iOS)

NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"none "];

id temp = [[NSAttributedString alloc] initWithString:@"bold " attributes:@{NSFontAttributeName: [UIFont boldSystemFontOfSize:12]}];
[str appendAttributedString:temp];

temp = [[NSAttributedString alloc] initWithString:@"italic " attributes:@{NSFontAttributeName: [UIFont italicSystemFontOfSize:12]}];
[str appendAttributedString:temp];

temp = [[NSAttributedString alloc] initWithString:@"none " attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:12]}];
[str appendAttributedString:temp];

temp = [[NSAttributedString alloc] initWithString:@"bold2 " attributes:@{NSFontAttributeName: [UIFont boldSystemFontOfSize:12]}];
[str appendAttributedString:temp];

self.label.attributedText = str;

NSMutableString *italics = [NSMutableString string];
NSMutableString *bolds = [NSMutableString string];
NSMutableString *normals = [NSMutableString string];

for (int i=0; i<str.length; i++) {
    //could be tuned: MOSTLY by taking into account the effective range and not checking 1 per 1
    //warn: == might work now but maybe i'd be cooler to check font traits using CoreText
    UIFont *font = [str attribute:NSFontAttributeName atIndex:i effectiveRange:nil];
    if(font == [UIFont italicSystemFontOfSize:12]) {
        [italics appendString:[[str mutableString] substringWithRange:NSMakeRange(i, 1)]];
    } else if(font == [UIFont boldSystemFontOfSize:12]){
        [bolds appendString:[[str mutableString] substringWithRange:NSMakeRange(i, 1)]];
    } else {
        [normals appendString:[[str mutableString] substringWithRange:NSMakeRange(i, 1)]];
    }
}

NSLog(@"%@", italics);
NSLog(@"%@", bolds);
NSLog(@"%@", normals);

Now here is how to find it. Deducing a selection range from this should be easy peasy :)

Note: you can only have a continuous selection! neither on osx nor on ios can you select n parts of a textfield/textview

Upvotes: 7

Related Questions