使用NSAttributedString的UItextview中的字符属性范围?

时间:2014-01-30 09:13:25

标签: ios uitextview nsattributedstring

我在UITextview

中有以下文字
  

您好!   右上方的汽车是您设置汽车规格的地方 - 不用担心,只需30秒,您只需要设置一次!

我想:

  1. 加粗“你好!”并使其大小超过17
  2. 强调“仅30秒”
  3. 制作“一次!”红色。
  4. 我该怎么做?我对NSAttributedString知之甚少,对文档也没有好运。

    谢谢你

2 个答案:

答案 0 :(得分:2)

如果您想通过故事板实现此目的,请选择UITextView&转到属性检查器。然后看下面的图片

enter image description here

如果以编程方式,请检查这些link&& Here

答案 1 :(得分:1)

创建Mutable Attributed字符串,执行以下步骤

NSMutableAttributedString * attrString = [[NSMutableAttributedString alloc] initWithString:yourTextView.text];

1)找到Hello!范围并设置字体大小

NSRange foundRange = [attrString rangeOfString:@"Hello!"];
if (foundRange.location != NSNotFound)
{
    [attrString beginEditing];
    [attrString addAttribute: NSFontAttributeName
                   value:[[UIFont boldSystemFontOfSize:17] fontName]
                   range:boldedRange];
    [attrString endEditing];
}

2)only 30 seconds的搜索范围并设置下划线样式

foundRange = [attrString rangeOfString:@"only 30 seconds"];
if (foundRange.location != NSNotFound)
{
    [attrString beginEditing];
    [attrString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:1] range:foundRange];
    [attrString endEditing];
}

3)once!的搜索范围并设置描边颜色。

foundRange = [attrString rangeOfString:@"once!"];
if (foundRange.location != NSNotFound)
{
    [attrString beginEditing];
    [attrString addAttribute:NSStrokeColorAttributeName value:[UIColor redColor] range:foundRange];
    [attrString endEditing];
}

最后将属性字符串设置为textview

yourTextView.attributedText = attrString;

注意:上述内容仅适用于ios6+.