2013-03-08 73 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個部分

相關問題