2013-03-08 161 views
2

如何只选择粗体斜体用户在textField/textView中输入的文本?从textField中选择粗体和斜体文本

我们可以做一个选择的文本大胆斜体,强调这些三者的任意组合,但怎么样的,反之亦然。

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

编辑:

我试图通过属性串阅读的文本为:

NSAttributedString *string=self.textView.string; 

但作为TextView的文本框和返回NSString所以所有格式都不见了。

+0

他们返回attributedText过iOS和OSX上attributedStringValue – 2013-03-08 13:09:36

+0

@ Daij-Djan:是的,我检查它的存在,谢谢,现在我可以做什么它。 :) – 2013-03-08 13:15:48

+0

问题仍然是'开放' - 答案不正确? – 2014-06-09 21:14:08

回答

7

iOS上使用attributedText性能与标签/文本框

在OSX使用attributedStringValue

,那么你可以通过attributedText的属性枚举,检查每个属性。伊利诺伊州鞭了一些代码(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); 

现在这里是如何找到它。从这里推导出一个选择范围应该是很容易的:)

注意:你只能连续选择!既不在OSX也不在iOS上,你可以选择一个文本框/ TextView中的n个部分

相关问题