如何在iOS中使字符串的一部分变为粗体?

时间:2014-12-01 06:14:30

标签: ios string

我想将文本字符串的某些部分加粗。

例如:这是粗体。这是正常的字符串。

在Android中,可以通过使用spannable字符串轻松实现。在iOS中它的等价物是什么?

3 个答案:

答案 0 :(得分:23)

是的,可以使用NSAttributedString

来实现
NSString *yourString = @"This is to be bold. This is normal string.";
NSMutableAttributedString *yourAttributedString = [[NSMutableAttributedString alloc] initWithString:yourString];
NSString *boldString = @"This is to be bold";
NSRange boldRange = [yourString rangeOfString:boldString];
[yourAttributedString addAttribute: NSFontAttributeName value:[UIFont boldSystemFontOfSize:12] range:boldRange];
[yourLabel setAttributedText: yourAttributedString];

答案 1 :(得分:1)

Swift版本:

@IBOutlet var theLabel: UILabel!
@IBOutlet var theTextview: UITextView!

        let theString = "Please satisfy three of the following password conditions" as NSString
        let theAttributedString = NSMutableAttributedString(string: theString as String)

        let boldString = "three"
        let boldRange = theString.range(of: boldString)
        let font = UIFont.boldSystemFont(ofSize: 20)

        theAttributedString.addAttribute(NSFontAttributeName, value: font, range: boldRange)
        theLabel.attributedText = theAttributedString
        theTextview.attributedText = theAttributedString

答案 2 :(得分:0)

您可以使用NSMutableAttributedString实现此目的。

参考Apple docs about NSMutableAttributedString

我尝试使用this answer's代码在UILabel中获取粗体和普通字体。