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

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

例如: 这是大胆的。 这是正常的字符串。

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

是的,可以使用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]; 
 NSString *text = @"Hello"; NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:text]; [attributedText addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:13.0] range:NSMakeRange(0, text.length-2)]; 

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

请参阅有关NSMutableAttributedString的Apple文档 。

我试过这个答案的代码,在UILabel中获得粗体和普通字体。

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