单个UILabel中的粗体和非粗体文字?

Dom*_*chi 244 objective-c nsattributedstring uilabel ios swift

如何在uiLabel中包含粗体和非粗体文本?

我宁愿不使用UIWebView ..我也读过这可能是使用NSAttributedString,但我不知道如何使用它.有任何想法吗?

Apple在他们的几个应用程序中实现了这一点; 示例截图:链接文字

谢谢! - Dom

nac*_*o4d 355

Swift3的更新

在Swift中我们不需要处理iOS5旧的东西,除了语法更短,所以一切都变得非常简单:

func attributedString(from string: String, nonBoldRange: NSRange?) -> NSAttributedString {
    let fontSize = UIFont.systemFontSize
    let attrs = [
        NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: fontSize),
        NSAttributedString.Key.foregroundColor: UIColor.black
    ]
    let nonBoldAttribute = [
        NSAttributedString.Key.font: UIFont.systemFont(ofSize: fontSize),
    ]
    let attrStr = NSMutableAttributedString(string: string, attributes: attrs)
    if let range = nonBoldRange {
        attrStr.setAttributes(nonBoldAttribute, range: range)
    }
    return attrStr
}
Run Code Online (Sandbox Code Playgroud)

用法:

func attributedString(from string: String, nonBoldRange: NSRange?) -> NSAttributedString {
    let fontSize = UIFont.systemFontSize
    let attrs = [
        NSFontAttributeName: UIFont.boldSystemFont(ofSize: fontSize),
        NSForegroundColorAttributeName: UIColor.black
    ]
    let nonBoldAttribute = [
        NSFontAttributeName: UIFont.systemFont(ofSize: fontSize),
    ]
    let attrStr = NSMutableAttributedString(string: string, attributes: attrs)
    if let range = nonBoldRange {
        attrStr.setAttributes(nonBoldAttribute, range: range)
    }
    return attrStr
}
Run Code Online (Sandbox Code Playgroud)

奖金:国际化

有人评论国际化.我个人认为这超出了这个问题的范围,但出于教学目的,我就是这样做的

let targetString = "Updated 2012/10/14 21:59 PM"
let range = NSMakeRange(7, 12)

let label = UILabel(frame: CGRect(x:0, y:0, width:350, height:44))
label.backgroundColor = UIColor.white
label.attributedText = attributedString(from: targetString, nonBoldRange: range)
label.sizeToFit()
Run Code Online (Sandbox Code Playgroud)

结果(假设有英语和日语Localizable.strings可用)

在此输入图像描述

在此输入图像描述


以前的iOS6及更高版本的答案(Objective-C仍然有效):

在iOS6的UILabel,UIButton,UITextView,UITextField,支持归属字符串,这意味着我们并不需要创建CATextLayerS作为我们的归因串收件人.此外,为了生成属性字符串,我们不再需要使用CoreText了:)我们在obj-c Foundation.framework NSParagraphStyle和类似的其他常量中有新的类,这将使我们的生活更轻松.好极了!

所以,如果我们有这个字符串:

// Date we want to show
let date = Date()

// Create the string.
// I don't set the locale because the default locale of the formatter is `NSLocale.current` so it's good for internationalisation :p
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .short
let targetString = String(format: NSLocalizedString("Update %@", comment: "Updated string format"),
                          formatter.string(from: date))

// Find the range of the non-bold part
formatter.timeStyle = .none
let nonBoldRange = targetString.range(of: formatter.string(from: date))

// Convert Range<Int> into NSRange
let nonBoldNSRange: NSRange? = nonBoldRange == nil ?
    nil :
    NSMakeRange(targetString.distance(from: targetString.startIndex, to: nonBoldRange!.lowerBound),
                targetString.distance(from: nonBoldRange!.lowerBound, to: nonBoldRange!.upperBound))

// Now just build the attributed string as before :)
label.attributedText = attributedString(from: targetString,
                                        nonBoldRange: nonBoldNSRange)
Run Code Online (Sandbox Code Playgroud)

我们只需要创建属性字符串:

NSString *text = @"Updated: 2012/10/14 21:59"
Run Code Online (Sandbox Code Playgroud)

有几个很好的入门博客文章在这里从球员invasivecode与更多的例子解释了使用的NSAttributedString,找"介绍NSAttributedString为iOS 6""归于字符串使用Interface Builder iOS的" :)

PS:上面的代码它应该工作,但它是脑编译.我希望它足够了:)


适用于iOS5及以下版本的旧答案

使用带有NSAttributedString的CATextLayer!比2 UILabels更轻,更简单.(iOS 3.2及以上版本)

例.

不要忘记添加QuartzCore框架(CALayers需要)和CoreText(属性字符串需要).

if ([_label respondsToSelector:@selector(setAttributedText:)])
{
    // iOS6 and above : Use NSAttributedStrings

    // Create the attributes
    const CGFloat fontSize = 13;
    NSDictionary *attrs = @{
        NSFontAttributeName:[UIFont boldSystemFontOfSize:fontSize],
        NSForegroundColorAttributeName:[UIColor whiteColor]
    };
    NSDictionary *subAttrs = @{
        NSFontAttributeName:[UIFont systemFontOfSize:fontSize]
    };

    // Range of " 2012/10/14 " is (8,12). Ideally it shouldn't be hardcoded
    // This example is about attributed strings in one label
    // not about internationalisation, so we keep it simple :)
    // For internationalisation example see above code in swift
    const NSRange range = NSMakeRange(8,12);

    // Create the attributed string (text + attributes)
    NSMutableAttributedString *attributedText =
      [[NSMutableAttributedString alloc] initWithString:text
                                             attributes:attrs];
    [attributedText setAttributes:subAttrs range:range];

    // Set it in our UILabel and we are done!
    [_label setAttributedText:attributedText];
} else {
    // iOS5 and below
    // Here we have some options too. The first one is to do something
    // less fancy and show it just as plain text without attributes.
    // The second is to use CoreText and get similar results with a bit
    // more of code. Interested people please look down the old answer.

    // Now I am just being lazy so :p
    [_label setText:text];
}
Run Code Online (Sandbox Code Playgroud)

下面的示例将向导航控制器的工具栏添加一个子图层.在iPhone中使用Mail.app.:)

#import <QuartzCore/QuartzCore.h>
#import <CoreText/CoreText.h>
Run Code Online (Sandbox Code Playgroud)

在这个例子中,我只有两种不同类型的字体(粗体和普通),但你也可以有不同的字体大小,不同的颜色,斜体,下划线等.看看NSAttributedString/NSMutableAttributedStringCoreText属性字符串键.

希望能帮助到你

  • 不幸的是,这个(以及其他答案)并不是国际化的.像Android上的Html标签支持(<b>,<i>)会很棒. (2认同)

bbr*_*ame 83

在UILabel上尝试一个类别:

以下是它的使用方法:

myLabel.text = @"Updated: 2012/10/14 21:59 PM";
[myLabel boldSubstring: @"Updated:"];
[myLabel boldSubstring: @"21:59 PM"];
Run Code Online (Sandbox Code Playgroud)

这是类别

的UILabel + Boldify.h

- (void) boldSubstring: (NSString*) substring;
- (void) boldRange: (NSRange) range;
Run Code Online (Sandbox Code Playgroud)

的UILabel + Boldify.m

- (void) boldRange: (NSRange) range {
    if (![self respondsToSelector:@selector(setAttributedText:)]) {
        return;
    }
    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
    [attributedText setAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:self.font.pointSize]} range:range];

    self.attributedText = attributedText;    
}

- (void) boldSubstring: (NSString*) substring {
    NSRange range = [self.text rangeOfString:substring];
    [self boldRange:range];
}
Run Code Online (Sandbox Code Playgroud)

请注意,这仅适用于iOS 6及更高版本.它将在iOS 5及更早版本中被忽略.

  • 不错的类别.虽然它不会使字体变粗.为了做到这一点,你应该这样做:`@ {NSFontAttributeName:[UIFont boldSystemFontOfSize:self.font.pointSize]}`我upvoted (2认同)

Ant*_*nko 48

Interface Builder中这很容易做到:

1)使UILabel 归因Attributes Inspector

大胆的例子步骤1

2)选择要加粗的短语部分

大胆的例子第2步

3)在字体选择器中更改其字体(或相同字体的粗体字体)

大胆的例子第3步

就这样!

  • 看起来,它很适合静态文本,反正我在阅读这篇文章之前不知道这一点. (2认同)
  • 我将我的文本的某些部分加粗,它显示了它应该如何出现在属性检查器中,而不是在模拟器中,甚至在故事板中。 (2认同)

Cra*_*urt 45

有基于bbrame类别的类别.它的工作原理类似,但允许您UILabel使用累积结果多次加粗.

的UILabel + Boldify.h

@interface UILabel (Boldify)
- (void) boldSubstring: (NSString*) substring;
- (void) boldRange: (NSRange) range;
@end
Run Code Online (Sandbox Code Playgroud)

的UILabel + Boldify.m

@implementation UILabel (Boldify)
- (void)boldRange:(NSRange)range {
    if (![self respondsToSelector:@selector(setAttributedText:)]) {
        return;
    }
    NSMutableAttributedString *attributedText;
    if (!self.attributedText) {
        attributedText = [[NSMutableAttributedString alloc] initWithString:self.text];
    } else {
        attributedText = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
    }
    [attributedText setAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:self.font.pointSize]} range:range];
    self.attributedText = attributedText;
}

- (void)boldSubstring:(NSString*)substring {
    NSRange range = [self.text rangeOfString:substring];
    [self boldRange:range];
}
@end
Run Code Online (Sandbox Code Playgroud)

通过此更正,您可以多次使用它,例如:

myLabel.text = @"Updated: 2012/10/14 21:59 PM";
[myLabel boldSubstring: @"Updated:"];
[myLabel boldSubstring: @"21:59 PM"];
Run Code Online (Sandbox Code Playgroud)

将导致:" 更新: 2012/10/14 21:59 PM ".


Pra*_*tha 26

它对我有用:

CGFloat boldTextFontSize = 17.0f;

myLabel.text = [NSString stringWithFormat:@"%@ 2012/10/14 %@",@"Updated:",@"21:59 PM"];

NSRange range1 = [myLabel.text rangeOfString:@"Updated:"];
NSRange range2 = [myLabel.text rangeOfString:@"21:59 PM"];

NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:myLabel.text];

[attributedText setAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:boldTextFontSize]}
                        range:range1];
[attributedText setAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:boldTextFontSize]}
                        range:range2];

myLabel.attributedText = attributedText;
Run Code Online (Sandbox Code Playgroud)

对于Swift版本:请参阅此处


Art*_*aev 25

我采用了Crazy Yoghurt对swift扩展的回答.

extension UILabel {

    func boldRange(_ range: Range<String.Index>) {
        if let text = self.attributedText {
            let attr = NSMutableAttributedString(attributedString: text)
            let start = text.string.characters.distance(from: text.string.startIndex, to: range.lowerBound)
            let length = text.string.characters.distance(from: range.lowerBound, to: range.upperBound)
            attr.addAttributes([NSFontAttributeName: UIFont.boldSystemFont(ofSize: self.font.pointSize)], range: NSMakeRange(start, length))
            self.attributedText = attr
        }
    }

    func boldSubstring(_ substr: String) {
        if let text = self.attributedText {
            var range = text.string.range(of: substr)
            let attr = NSMutableAttributedString(attributedString: text)
            while range != nil {
                let start = text.string.characters.distance(from: text.string.startIndex, to: range!.lowerBound)
                let length = text.string.characters.distance(from: range!.lowerBound, to: range!.upperBound)
                var nsRange = NSMakeRange(start, length)
                let font = attr.attribute(NSFontAttributeName, at: start, effectiveRange: &nsRange) as! UIFont
                if !font.fontDescriptor.symbolicTraits.contains(.traitBold) {
                    break
                }
                range = text.string.range(of: substr, options: NSString.CompareOptions.literal, range: range!.upperBound..<text.string.endIndex, locale: nil)
            }
            if let r = range {
                boldRange(r)
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

可能是Range和NSRange之间没有很好的转换,但我没有找到更好的东西.


mat*_*ttt 21

查看TTTAttributedLabel.它是UILabel的直接替代品,允许您通过将NSAttributedString设置为该标签的文本,在单个标签中添加混合字体和颜色.

  • 同意使用替换掉(有几个左右).Apple还没有完成这方面的工作.除了作为一个学术练习,我认为不值得尝试理解和实现这个混乱 - 无论如何,它可能会在下一个版本(或左右)中得到很好的整理.:) https://github.com/AliSoftware/OHAttributedLabel (5认同)

x4h*_*h1d 12

在这种情况下你可以尝试,

UILabel *displayLabel = [[UILabel alloc] initWithFrame:/*label frame*/];
displayLabel.font = [UIFont boldSystemFontOfSize:/*bold font size*/];

NSMutableAttributedString *notifyingStr = [[NSMutableAttributedString alloc] initWithString:@"Updated: 2012/10/14 21:59 PM"];
[notifyingStr beginEditing];
[notifyingStr addAttribute:NSFontAttributeName
                     value:[UIFont systemFontOfSize:/*normal font size*/]
                     range:NSMakeRange(8,10)/*range of normal string, e.g. 2012/10/14*/];
[notifyingStr endEditing];

displayLabel.attributedText = notifyingStr; // or [displayLabel setAttributedText: notifyingStr];
Run Code Online (Sandbox Code Playgroud)


小智 8

在UILabel中使文本变为粗体和下划线.只需在代码中添加以下行.

NSRange range1 = [lblTermsAndCondition.text rangeOfString:NSLocalizedString(@"bold_terms", @"")];
NSRange range2 = [lblTermsAndCondition.text rangeOfString:NSLocalizedString(@"bold_policy", @"")];
NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:lblTermsAndCondition.text];
[attributedText setAttributes:@{NSFontAttributeName:[UIFont fontWithName:fontBold size:12.0]}
                        range:range1];
[attributedText setAttributes:@{NSFontAttributeName:[UIFont fontWithName:fontBold size:12.0]}
                        range:range2];


[attributedText addAttribute:(NSString*)kCTUnderlineStyleAttributeName
                  value:[NSNumber numberWithInt:kCTUnderlineStyleSingle]
                  range:range1];

[attributedText addAttribute:(NSString*)kCTUnderlineStyleAttributeName
                       value:[NSNumber numberWithInt:kCTUnderlineStyleSingle]
                       range:range2];



lblTermsAndCondition.attributedText = attributedText;
Run Code Online (Sandbox Code Playgroud)


小智 5

使用下面的代码。希望对您有帮助。

NSString *needToChangeStr=@"BOOK";
NSString *display_string=[NSString stringWithFormat:@"This is %@",book];

NSMutableAttributedString *attri_str=[[NSMutableAttributedString alloc]initWithString:display_string];

int begin=[display_string length]-[needToChangeStr length];
int end=[needToChangeStr length];


[attri_str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:30] range:NSMakeRange(begin, end)];
Run Code Online (Sandbox Code Playgroud)


Vin*_*cob 5

斯威夫特 4:

// attribute with color red and Bold
var attrs1 = [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 20), NSAttributedStringKey.foregroundColor: UIColor.red]

// attribute with color black and Non Bold
var attrs2 = [NSAttributedStringKey.font: UIFont(name: "Roboto-Regular", size: 20), NSAttributedStringKey.foregroundColor: UIColor.black]  

var color1 = NSAttributedString(string: "RED", attributes: attrs1)

var color2 = NSAttributedString(string: " BLACK", attributes: attrs2)

var string = NSMutableAttributedString()

string.append(color1)

string.append(color2)

// print the text with **RED** BLACK
print("Final String : \(string)")
Run Code Online (Sandbox Code Playgroud)