[英]Select Bold and Italicized text from textField
如何在textField / textView中僅選擇用戶輸入的粗體和斜體文本?
我們可以將選定的文本加粗 , 斜體 ,下划線以及這三者的任意組合,但反之亦然。
* 這不是特定於Mac OSX或iOS,任何一個解決方案對我都有好處。
編輯:
我嘗試通過閱讀屬性字符串中的文本:
NSAttributedString *string=self.textView.string;
但是,當textView和textField返回NSString
,所有格式都消失了。
在iOS上使用attributesText屬性與標簽/文本字段
在OSX上使用attributedStringValue
然后,您可以枚舉attributionText的屬性並檢查每個屬性。 生病了一些代碼(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);
現在這里是如何找到它。 從這個推斷選擇范圍應該很容易peasy :)
注意:您只能連續選擇! 無論是在osx上還是在ios上都可以選擇文本域/文本視圖的n個部分
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.