NSAttributedString将样式更改为粗体而不更改pointSize吗? [英] NSAttributedString change style to bold without changing pointSize?

查看:80
本文介绍了NSAttributedString将样式更改为粗体而不更改pointSize吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究iOS上的NSAttributedString.我有一个模型,该模型将人的姓氏和名字返回为NSAttributesString. (我不知道在模型中处理属性字符串是否是个好主意!?)我希望将名字打印在常规位置,因为姓氏应以粗体显示.我不需要的是设置文本大小.到目前为止,我发现的只是:

I am digging into NSAttributedStrings on iOS. I have a model that is returning a persons first and last name as NSAttributesString. (I don't know if it is a good idea to deal with attributed strings in models!?) I want the first name to be printed regular where as the last name should be printed in bold. What I don't want is to set a text size. All I found so far is this:

- (NSAttributedString*)attributedName {
    NSMutableAttributedString* name = [[NSMutableAttributedString alloc] initWithString:self.name];
    [name setAttributes:@{NSFontAttributeName : [UIFont boldSystemFontOfSize:[UIFont systemFontSize]]} range:[self.name rangeOfString:self.lastname]];
    return name;
}

但是,这当然会覆盖姓氏的字体大小,这会在UITableViewCell中产生非常有趣的外观,其中<名字>将按单元格标签的常规文本大小打印名字,最后一个名称将被打印得很小.

However, this will, of course, override the font size of the last name, which gives a very funny look in a UITableViewCell where the first name will be printed in the regular text size of the cell's label and the last name will be printed very small.

有什么方法可以实现我想要的吗?

Is there any way to achieve what I want?

感谢您的帮助!

推荐答案

这是Swift extension,它使文本加粗,同时保留当前字体属性(和文本大小).

Here's a Swift extension that makes text bold, while preserving the current font attributes (and text size).

public extension UILabel {

    /// Makes the text bold.
    public func makeBold() {
        //get the UILabel's fontDescriptor
        let desc = self.font.fontDescriptor.withSymbolicTraits(.traitBold)
        //Setting size to '0.0' will preserve the textSize
        self.font = UIFont(descriptor: desc, size: 0.0)
    }

}

这篇关于NSAttributedString将样式更改为粗体而不更改pointSize吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆