Select bold and italic text from textField

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

We can make the selected text bold , italicized, underline, and any combination of the three, but vice versa.

* This does not apply to Mac OSX or iOS, a solution in one of them is suitable for me.

EDIT:

I tried to read the text in the attribute string as:

NSAttributedString *string=self.textView.string; 

But since textView and textField return NSString , so all formatting has disappeared.

+2
source share
1 answer

iOS uses attributedText attributes with labels / text fields

on OSX use attribStringValue

you can list attributedText attributes and check each attribute. Ill hack some code (osx and 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's how to find it. Selecting a range of choices from this should be easy peasy :)

Note: you can only have continuous choices! neither on osx nor on ios you can select n parts of the text field / textview

+7
source

All Articles