从textField中select粗体和斜体文本

我如何只select用户在textField / textView中input的粗体斜体文本?

我们可以使选定的文本大胆斜体 ,下划线和这三者的任意组合,但反之亦然。

* 这不是特定于Mac OSX或iOS,任何一个解决scheme都适合我。

编辑:

我尝试阅读属性string中的文本:

NSAttributedString *string=self.textView.string; 

但是,由于textView和textField返回NSString所以所有的格式不见了。

在iOS上使用标签/文本字段的属性文本属性

在OSX上使用的attributesStringValue

然后您可以枚举属性文本的属性并检查每个属性。 病鞭起一些代码(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); 

现在,这里是如何find它。 从这个推导出一个select范围应该是容易的pe 🙂 🙂

注意:你只能有一个连续的select! 在osx和ios上都不能select文本框/文本框的n个部分