在 iOS UILabel 上设置 BOLD 字体

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18862868/
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-31 01:18:01  来源:igfitidea点击:

Setting BOLD font on iOS UILabel

iosobjective-cfontsuifont

提问by tech_human

I have assigned a custom font of 'Helvetica' with size 14 already for the text in UILabel using Interface Builder.

我已经使用界面生成器为 UILabel 中的文本分配了大小为 14 的“Helvetica”自定义字体。

I am using reusing the same label at multiple places, but at some place I have to display the text in bold.

我在多个地方重复使用相同的标签,但在某些地方我必须以粗体显示文本。

Is there any way I can just specify to make the existing font bold instead of creating the whole UIFont again? This is what I do now:

有什么方法可以指定使现有字体加粗而不是再次创建整个 UIFont 吗?这就是我现在所做的:

myLabel.font = [UIFont fontWithName:@"Helvetica Neue" size:14];

回答by Maksymilian Wojakowski

It's a fishy business to mess with the font names. And supposedly you have an italic font and you wanna make it bold - adding simply @"-Bold"to the name doesn't work. There's much more elegant way:

弄乱字体名称是一项可疑的业务。据说你有一个斜体字体,你想让它加粗 - 简单@"-Bold"地添加到名称中是行不通的。还有更优雅的方式:

- (UIFont *)boldFontWithFont:(UIFont *)font
{
    UIFontDescriptor * fontD = [font.fontDescriptor
                fontDescriptorWithSymbolicTraits:UIFontDescriptorTraitBold];
    return [UIFont fontWithDescriptor:fontD size:0];
}

size:0means 'keep the size as it is in the descriptor'. You might find useful UIFontDescriptorTraitItalictrait if you need to get an italic font

size:0表示“保持描述符中的大小”。UIFontDescriptorTraitItalic如果您需要获得斜体字体,您可能会发现有用的特征

In Swift it would be nice to write a simple extension:

在 Swift 中编写一个简单的扩展会很好:

extension UIFont {

    func withTraits(traits:UIFontDescriptorSymbolicTraits...) -> UIFont {
        let descriptor = self.fontDescriptor().fontDescriptorWithSymbolicTraits(UIFontDescriptorSymbolicTraits(traits))
        return UIFont(descriptor: descriptor, size: 0)
    }

    func bold() -> UIFont {
        return withTraits(.TraitBold)
    }

    func italic() -> UIFont {
        return withTraits(.TraitItalic)
    }

    func boldItalic() -> UIFont {
        return withTraits(.TraitBold, .TraitItalic)
    }

}

Then you may use it this way:

那么你可以这样使用它:

myLabel.font = myLabel.font.boldItalic()

myLabel.font = myLabel.font.bold()

myLabel.font = myLabel.font.withTraits(.TraitCondensed, .TraitBold, .TraitItalic)

回答by LE SANG

UPDATE:
Starting with iOS 8, messing with font names is no longer needed. Instead see newer answers that use UIFontDescriptorSymbolicTraits: hereand here.

更新:
从 iOS 8 开始,不再需要弄乱字体名称。而是查看使用UIFontDescriptorSymbolicTraits: herehere 的较新答案。



myLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:14];

If you wanna set it programmatically,you must check bold type is support or not in iOS, normally Bold or Italic will have format FontName-Bold, FontName-Italic, FontName-BoldItalic.

如果你想以编程方式设置它,你必须检查 iOS 是否支持粗体,通常粗体或斜体的格式为 FontName-Bold、FontName-Italic、FontName-BoldItalic。

Now, write a bold function

现在,写一个粗体函数

-(void)boldFontForLabel:(UILabel *)label{
    UIFont *currentFont = label.font;
    UIFont *newFont = [UIFont fontWithName:[NSString stringWithFormat:@"%@-Bold",currentFont.fontName] size:currentFont.pointSize];
    label.font = newFont;
}

Then call it

然后调用它

[self boldFontForLabel:yourLabel];

回答by thatzprem

UIFont* boldFont = [UIFont boldSystemFontOfSize:[UIFont systemFontSize]];
[myLabel setFont:boldFont];

回答by cscott530

Extending thisanswer, in swift:

迅速扩展这个答案:

extension UIFont {
    func bold() -> UIFont {
        let descriptor = self.fontDescriptor().fontDescriptorWithSymbolicTraits(UIFontDescriptorSymbolicTraits.TraitBold)
        return UIFont(descriptor: descriptor, size: 0)
    }
}

回答by Jasmeet

We just need the right font name. I find that iOSFonts.com is the most helpful resource for knowing exactly what name to use.

我们只需要正确的字体名称。我发现 iOSFonts.com 是准确了解要使用的名称的最有用的资源。

You can set Bold + ITALIC, by using FONT NAME "Arial-BoldItalicMT"

您可以使用字体名称“Arial-BoldItalicMT”设置粗体+斜体

It works in every Case:

它适用于每种情况:

[myLabel setFont:[UIFont fontWithName:@"Arial-BoldItalicMT" size:17]];

回答by RyanPliske

I did mine a little differently with Swift

我用Swift做的有点不同

var boldHelveticaFont = UIFont(name: "Helvetica Neue", size: 40)?.fontDescriptor().fontDescriptorWithSymbolicTraits(UIFontDescriptorSymbolicTraits.TraitBold)
self.InstructionsTextView.font = UIFont(descriptor: boldHelveticaFont!, size: 40)

回答by ingconti

for "swifters" give a try.

对于“快速者”,请尝试一下。

this sample controller will show 4 labels with all the variants.

此示例控制器将显示 4 个带有所有变体的标签。

import UIKit

class ViewController: UIViewController {


    var labl: UILabel?
    var labl2: UILabel?
    var labl3: UILabel?
    var labl4: UILabel?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let font = UIFont.systemFontOfSize(32)
        labl = UILabel(frame: CGRectMake(20,20,400, 45))
        labl!.text = "Attention:"
        labl!.font = font

        labl2 = UILabel(frame: CGRectMake(20,60,400, 45))
        labl2!.text = "Attention:"
        labl2!.font = bold(font)

        labl3 = UILabel(frame: CGRectMake(20,100,400, 45))
        labl3!.text = "Attention:"
        labl3!.font = italic(font)

        labl4 = UILabel(frame: CGRectMake(20,140,400, 45))
        labl4!.text = "Attention:"
        labl4!.font = boldAndItalic(font)



        self.view.addSubview(labl!)
        self.view.addSubview(labl2!)
        self.view.addSubview(labl3!)
        self.view.addSubview(labl4!)


    }

    // nice to write an extension...
    func bold(font: UIFont) -> UIFont {
        let descriptor = font.fontDescriptor().fontDescriptorWithSymbolicTraits([.TraitBold])
        return UIFont(descriptor: descriptor, size: 0)
    }

    func boldAndItalic(font: UIFont) -> UIFont {
        let descriptor = font.fontDescriptor().fontDescriptorWithSymbolicTraits([.TraitBold, .TraitItalic])
        return UIFont(descriptor: descriptor, size: 0)
    }

    func italic(font: UIFont) -> UIFont {
        let descriptor = font.fontDescriptor().fontDescriptorWithSymbolicTraits([.TraitItalic])
        return UIFont(descriptor: descriptor, size: 0)
    }
}

wulld be nice to write an extension for UIFont class.

为 UIFont 类编写扩展会很好。

回答by David West

You probably don't need an "extension" as such, if you want this for any custom fonts...

你可能不需要这样的“扩展”,如果你想要任何自定义字体......

Just add a function (similar to some above) that you can call from anywhere (i.e. without a class) and then you can embolden words within any string, on numerous occasions by calling just ONE LINEof code:

只需添加一个您可以从任何地方(即没有类)调用的函数(类似于上面的一些),然后您就可以在任何字符串中添加单词,在很多情况下只需调用一行代码:

To go in a file like constants.swift:

进入像constants.swift这样的文件:

import Foundation
import UIKit

func addBoldText(fullString: NSString, boldPartOfString: NSString, font: UIFont!, boldFont: UIFont!) -> NSAttributedString {
   let nonBoldFontAttribute = [NSFontAttributeName:font!]
   let boldFontAttribute = [NSFontAttributeName:boldFont]
   let boldString = NSMutableAttributedString(string: fullString as String, attributes:nonBoldFontAttribute)
   boldString.addAttributes(boldFontAttribute, range: fullString.rangeOfString(boldPartOfString as String))
   return boldString
}

Then you can just call this one line of code for any UILabel:

然后你可以为任何 UILabel 调用这一行代码:

self.UILabel.attributedText = addBoldText("Check again in 30 DAYS to find more friends", boldPartOfString: "30 DAYS", font: normalFont!, boldFont: boldSearchFont!)


//Mark: Albeit that you've had to define these somewhere:

let normalFont = UIFont(name: "INSERT FONT NAME", size: 15)
let boldFont = UIFont(name: "INSERT BOLD FONT", size: 15)

回答by Kevin ABRIOUX

My contribution with an extension for UILabel updated for Swift 4 :

我为 Swift 4 更新了 UILabel 扩展的贡献:

extension UILabel{
    func bold() -> UILabel {
        if let descriptor = self.font.fontDescriptor.withSymbolicTraits(UIFontDescriptor.SymbolicTraits.traitBold){
            self.font = UIFont(descriptor: descriptor, size: 0)
        }
        return self
    }
}

Just call .bold() like that :

只需像这样调用 .bold() :

let myLabel = UILabel()
myLabel.bold()

回答by user2643679

let boldHelveticaFont = UIFont(name: "HelveticaNeue", size: 25)?.fontDescriptor.withSymbolicTraits(UIFontDescriptor.SymbolicTraits.traitBold)
label.font = UIFont(descriptor: boldHelveticaFont!, size: 25)