NSAttributedString将样式更改为粗体而不更改pointSize?

Mic*_*chs 16 iphone nsattributedstring uifont ipad ios

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

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

但是,这当然会覆盖姓氏的字体大小,这样UITableViewCell可以在单元格标签的常规文本大小中打印出名字的位置非常有趣,并且姓氏将打印得非常小.

有没有办法实现我想要的?

谢谢你的帮助!

Yon*_*nat 7

StrokeWidth通过将属性设置为负值,可以将字符串加粗而不更改其其他属性。

Objective-C:

[name setAttributes:@{NSStrokeWidthAttributeName : @-3.0} range:NSRangeFromString(name.string)];
Run Code Online (Sandbox Code Playgroud)

迅速:

name.setAttributes([.strokeWidth: NSNumber(value: -3.0)], range: NSRangeFromString(name.string))
Run Code Online (Sandbox Code Playgroud)


Sak*_*boy 5

这是一个Swift extension使文本加粗,同时保留当前字体属性(和文本大小)的方法。

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)
    }

}
Run Code Online (Sandbox Code Playgroud)


rma*_*ddy 2

从表格单元格代码进行上述调用,但通过从单元格的 textLabel 获取字体大小来传递所需的字体大小。

  • 如果您实现“tableView:willDisplayCellAtIndexPath:”委托方法,则应设置字体并且您可以在那里更新字体。 (3认同)