ios 任何方法来加粗 NSString 的一部分?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6013705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 19:56:05  来源:igfitidea点击:

Any way to bold part of a NSString?

objective-ciosnsstring

提问by Zhen

Is there any way to bold only part of a string? For example:

有没有办法只加粗字符串的一部分?例如:

Approximate Distance: 120maway

大约距离:120米

Thanks!

谢谢!

回答by Jacob Relkin

What you coulddo is use an NSAttributedString.

可以做的是使用一个NSAttributedString.

NSString *boldFontName = [[UIFont boldSystemFontOfSize:12] fontName];
NSString *yourString = ...;
NSRange boldedRange = NSMakeRange(22, 4);

NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:yourString];

[attrString beginEditing];
[attrString addAttribute:kCTFontAttributeName 
                   value:boldFontName
                   range:boldedRange];

[attrString endEditing];
//draw attrString here...

Take a look at this handy dandy guideto drawing NSAttributedStringobjects with Core Text.

看看这个NSAttributedString使用 Core Text绘制对象的方便的花花公子指南

回答by Chris Frederick

As Jacob mentioned, you probably want to use an NSAttributedStringor an NSMutableAttributedString. The following is one example of how you might do this.

正如 Jacob 提到的,您可能想要使用 anNSAttributedString或 an NSMutableAttributedString。以下是您可以如何执行此操作的一个示例。

NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"Approximate Distance: 120m away"];
NSRange selectedRange = NSMakeRange(22, 4); // 4 characters, starting at index 22

[string beginEditing];

[string addAttribute:NSFontAttributeName
           value:[NSFont fontWithName:@"Helvetica-Bold" size:12.0]
           range:selectedRange];

[string endEditing];

回答by yura

If you do not want to bother with fonts (as not every variation of font contains "Bold"), here is another way to do this. Please be aware, this is currently only available on OS X...:

如果您不想打扰字体(因为并非所有字体变体都包含“粗体”),这是另一种方法。请注意,这目前仅在 OS X 上可用...:

NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:"Approximate Distance: 120m away"];
[attrString beginEditing];
[attrString applyFontTraits:NSBoldFontMask
                      range:NSMakeRange(22, 4)];
[attrString endEditing];

回答by Andrew Marin

The code above gave me crash when I created UILabel with this attributedString.

当我用这个属性字符串创建 UILabel 时,上面的代码让我崩溃了。

I used this code and it worked:

我使用了这段代码并且它有效:

NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:string];
NSRange boldedRange = NSMakeRange(0, 1);
UIFont *fontText = [UIFont systemFontOfSize:12]; //[UIFont fontWithName:@"Lato-Bold" size:12];
NSDictionary *dictBoldText = [NSDictionary dictionaryWithObjectsAndKeys:fontText, NSFontAttributeName, nil];
[attrString setAttributes:dictBoldText range:boldedRange];

回答by Magoo

Swift

迅速

Also includes getting the range of the string you want to embolden dynamically

还包括获取要动态加粗的字符串的范围

let nameString = "Magoo"
let string = "Hello my name is \(nameString)"

let attributes = [NSFontAttributeName:UIFont.systemFontOfSize(14.0),NSForegroundColorAttributeName: UIColor.black]
let boldAttribute = [NSFontAttributeName:UIFont.boldSystemFontOfSize(14.0)]

let attributedString = NSMutableAttributedString(string: string, attributes: attributes)

let nsString = NSString(string: string)
let range = nsString.rangeOfString(nameString)

if range.length > 0 { attributedString.setAttributes(boldAttribute, range: range) }

someLabel.attributedText = attributedString

回答by Yonat

To bold a string without hardcoding its font, you can use the StrokeWidth attribute with a negative value:

要加粗字符串而不对其字体进行硬编码,您可以使用 StrokeWidth 属性和负值:

let s = NSMutableAttributedString(string: "Approximate Distance: 120m away")
s.addAttribute(NSStrokeWidthAttributeName, value: NSNumber(value: -3.0), range: NSRange(22..<26))

回答by aroth

An NSStringis just a data container. It doesn't contain any details about presentation concerns.

AnNSString只是一个数据容器。它不包含有关演示问题的任何详细信息。

It sounds like what you probably want to do is bold part of the UILabelthat is being used to display your string. Which I don't think you can do. But you could always break the UI down into three labels, one for "Approximate Distance:", one for "120 m", and one for "away". Place them in-line with each other and you should get the desired effect.

听起来您可能想要做的是UILabel用于显示字符串的粗体部分。我认为你做不到。但是您总是可以将 UI 分解为三个标签,一个用于“近似距离:”,一个用于“ 120 m”,一个用于“远离”。将它们相互对齐,您应该会获得所需的效果。

Another option might be to use a UIWebViewand a little bit of markup to display your string with embedded formatting information, as discussed here:

另一种选择可能是使用 aUIWebView和一点标记来显示带有嵌入格式信息的字符串,如下所述:

http://iphoneincubator.com/blog/windows-views/display-rich-text-using-a-uiwebview

http://iphoneincubator.com/blog/windows-views/display-rich-text-using-a-uiwebview

回答by Darius Miliauskas

I coupled @Jacob Relkin and @Andrew Marin answers, otherwise, I got the crashes. Here is the answer for iOS9:

我结合了@Jacob Relkin 和@Andrew Marin 的回答,否则,我会崩溃。这是iOS9的答案:

UIFont *boldFont = [UIFont boldSystemFontOfSize:12];
NSString *yourString = @"Approximate Distance: 120m away";
NSRange boldedRange = NSMakeRange(22, 4);

NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:yourString];

[attrString beginEditing];
[attrString addAttribute:NSFontAttributeName 
                   value:boldFont
                   range:boldedRange];

[attrString endEditing];

I took a look at the official documentation: 1and 2.

我看了一下官方文档:12

回答by Adi Rabi

In Xamarin ios you can bold part of a NSString this way:

在 Xamarin ios 中,您可以这样加粗 NSString 的一部分:

public static NSMutableAttributedString BoldRangeOfString (string str, float fontSize, int startRange, int lengthRange)
    {
        var firstAttributes = new UIStringAttributes {
            Font = UIFont.BoldSystemFontOfSize(fontSize)
        };

        NSMutableAttributedString boldString = new NSMutableAttributedString (str);
        boldString.SetAttributes (firstAttributes.Dictionary, new NSRange (startRange, lengthRange));
        return boldString;
    }    

and call this method:

并调用此方法:

myLabel = new UILabel (); 
...
myLabel.AttributedText = BoldRangeOfString("my text", fontSize, startRange, lengthRange);    

回答by Vette

Shorter way using Swift5+

使用 Swift5+ 的更短方法

let labelNotes = UILabel()  //or UITextView(), etc...
let attributedNotes = NSMutableAttributedString(string: "Bold: some stuff not bold")
attributedNotes.addAttribute(NSAttributedString.Key.font, value: UIFont.boldSystemFont(ofSize: 14), range: NSRange(location: 0, length: 5))
labelNotes.attributedText = attributedNotes