从textField中选择粗体和斜体文本

时间:2013-03-08 12:38:58

标签: ios objective-c macos cocoa

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

我们可以选择文字粗体斜体,下划线以及这三者的任意组合,但反之亦然。

* 这不是特定于Mac OSX或iOS,任何一个解决方案对我都有好处。

编辑:

我尝试通过阅读属性字符串中的文字:

NSAttributedString *string=self.textView.string;

但是当textView和textField返回NSString时,所有格式都消失了。

1 个答案:

答案 0 :(得分:7)

iOS上的

使用带有标签/文本字段的attributesText属性

OSX上的

使用了belongsStringValue

然后,您可以枚举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);

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

注意:您只能连续选择!在osx和ios上都不能选择textfield / textview的部分