【问题标题】:Select Bold and Italicized text from textField从 textField 中选择粗体和斜体文本
【发布时间】:2013-02-24 00:12:01
【问题描述】:

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

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

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

编辑:

我尝试将属性字符串中的文本读取为:

NSAttributedString *string=self.textView.string;

但由于 textView 和 textField 返回 NSString,所以所有格式都消失了。

【问题讨论】:

  • 它们在 ios 和 osx 上也返回属性文本属性字符串值
  • @Daij-Djan:是的,我在那里检查过,谢谢,现在我可以用它做点什么了。 :)
  • 问题仍然是“开放的” - 答案不正确吗?

标签: ios objective-c macos cocoa


【解决方案1】:

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

在 OSX 上使用属性字符串值

然后您可以枚举属性文本的属性并检查每个属性。我会编写一些代码(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 上都不能选择文本字段/文本视图的 n 部分

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多