在swift中使用属性string粗体文本

我有这样的一个string

var str = "@text1 this is good @text1" 

现在用另一个stringreplacetext1 ,比如t 1 。 我能够代替文本,但我不能大胆。 我想大胆的新stringt 1 ,以便最终的输出将是:

@t 1这是好的@t 1

我该怎么做?

我看到的所有例子都在Objective-C中,但我想在Swift中完成。

提前致谢。

这是一个很好的方法来在一个标签中使用粗体和普通文本的组合。

延期:

Swift 2.1

 extension NSMutableAttributedString { func bold(text:String) -> NSMutableAttributedString { let attrs:[String:AnyObject] = [NSFontAttributeName : UIFont(name: "AvenirNext-Medium", size: 12)!] let boldString = NSMutableAttributedString(string:"\(text)", attributes:attrs) self.appendAttributedString(boldString) return self } func normal(text:String)->NSMutableAttributedString { let normal = NSAttributedString(string: text) self.appendAttributedString(normal) return self } } 

Swift 3.0

 extension NSMutableAttributedString { @discardableResult func bold(_ text:String) -> NSMutableAttributedString { let attrs:[String:AnyObject] = [NSFontAttributeName: UIFont(name: "AvenirNext-Medium", size: 12)!] let boldString = NSMutableAttributedString(string: text, attributes:attrs) self.append(boldString) return self } @discardableResult func normal(_ text:String)->NSMutableAttributedString { let normal = NSAttributedString(string: text) self.append(normal) return self } } 

斯威夫特4

 extension NSMutableAttributedString { @discardableResult func bold(_ text: String) -> NSMutableAttributedString { let attrs: [NSAttributedStringKey: Any] = [.font: UIFont(name: "AvenirNext-Medium", size: 12)!] let boldString = NSMutableAttributedString(string:text, attributes: attrs) append(boldString) return self } @discardableResult func normal(_ text: String) -> NSMutableAttributedString { let normal = NSAttributedString(string: text) append(normal) return self } } 

用法:

 let formattedString = NSMutableAttributedString() formattedString .bold("Bold Text") .normal(" Normal Text ") .bold("Bold Text") let lbl = UILabel() lbl.attributedText = formattedString 

结果:

粗体文本正常文本粗体文本

 var normalText = "Hi am normal" var boldText = "And I am BOLD!" var attributedString = NSMutableAttributedString(string:normalText) var attrs = [NSFontAttributeName : UIFont.boldSystemFont(ofSize: 15)] var boldString = NSMutableAttributedString(string:boldText, attributes:attrs) attributedString.appendAttributedString(boldString) 

当你想把它分配给一个标签时:

 yourLabel.attributedText = attributedString 

编辑/更新: Xcode 8.3.2•Swift 3.1

如果您了解HTML和CSS,则可以使用它轻松控制字符样式,颜色和属性string的大小,如下所示:

 extension String { var html2AttStr: NSAttributedString? { return try? NSAttributedString(data: Data(utf8), options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue], documentAttributes: nil) } } "<style type=\"text/css\">#red{color:#F00}#green{color:#0F0}#blue{color: #00F; font-weight: Bold; font-size: 32}</style><span id=\"red\" >Red,</span><span id=\"green\" > Green </span><span id=\"blue\">and Blue</span>".html2AttStr 

这是我提出的最好的方式。 添加一个可以从任何地方调用的函数,并将其添加到文件中,而不需要像Constants.swift这样的类,然后通过调用一行代码就可以在任何string中强化单词:

要进入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 } 

然后,你可以为任何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) 

如果您正在使用本地化的string,则可能无法依靠始终处于句末的粗体string。 如果是这种情况,那么下面的工作很好:

例如查询“blah”不匹配任何项目

 /* Create the search query part of the text, eg "blah". The variable 'text' is just the value entered by the user. */ let searchQuery = "\"\(text)\"" /* Put the search text into the message */ let message = "Query \(searchQuery). does not match any items" /* Find the position of the search string. Cast to NSString as we want range to be of type NSRange, not Swift's Range<Index> */ let range = (message as NSString).rangeOfString(searchQuery) /* Make the text at the given range bold. Rather than hard-coding a text size, Use the text size configured in Interface Builder. */ let attributedString = NSMutableAttributedString(string: message) attributedString.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFontOfSize(label.font.pointSize), range: range) /* Put the text in a label */ label.attributedText = attributedString 

我扩展了David West的伟大的答案,以便您可以input一个string,并告诉它你想要的所有子string:

 func addBoldText(fullString: NSString, boldPartsOfString: Array<NSString>, font: UIFont!, boldFont: UIFont!) -> NSAttributedString { let nonBoldFontAttribute = [NSFontAttributeName:font!] let boldFontAttribute = [NSFontAttributeName:boldFont!] let boldString = NSMutableAttributedString(string: fullString as String, attributes:nonBoldFontAttribute) for i in 0 ..< boldPartsOfString.count { boldString.addAttributes(boldFontAttribute, range: fullString.rangeOfString(boldPartsOfString[i] as String)) } return boldString } 

然后像这样调用它:

 let normalFont = UIFont(name: "Dosis-Medium", size: 18) let boldSearchFont = UIFont(name: "Dosis-Bold", size: 18) self.UILabel.attributedText = addBoldText("Check again in 30 days to find more friends", boldPartsOfString: ["Check", "30 days", "find", "friends"], font: normalFont!, boldFont: boldSearchFont!) 

这将会增强你想要在给定string中加粗的所有子string

这可能是有用的

 class func createAttributedStringFrom (string1 : String ,strin2 : String, attributes1 : Dictionary<String, NSObject>, attributes2 : Dictionary<String, NSObject>) -> NSAttributedString{ let fullStringNormal = (string1 + strin2) as NSString let attributedFullString = NSMutableAttributedString(string: fullStringNormal as String) attributedFullString.addAttributes(attributes1, range: fullStringNormal.rangeOfString(string1)) attributedFullString.addAttributes(attributes2, range: fullStringNormal.rangeOfString(strin2)) return attributedFullString } 

基于杰里米·贝德(Jeremy Bader)和戴维·韦斯特(David West)的杰出答案,斯威夫特3延伸:

 extension String { func withBoldText(boldPartsOfString: Array<NSString>, font: UIFont!, boldFont: UIFont!) -> NSAttributedString { let nonBoldFontAttribute = [NSFontAttributeName:font!] let boldFontAttribute = [NSFontAttributeName:boldFont!] let boldString = NSMutableAttributedString(string: self as String, attributes:nonBoldFontAttribute) for i in 0 ..< boldPartsOfString.count { boldString.addAttributes(boldFontAttribute, range: (self as NSString).range(of: boldPartsOfString[i] as String)) } return boldString } } 

用法:

 let label = UILabel() let font = UIFont(name: "AvenirNext-Italic", size: 24)! let boldFont = UIFont(name: "AvenirNext-BoldItalic", size: 24)! label.attributedText = "Make sure your face is\nbrightly and evenly lit".withBoldText( boldPartsOfString: ["brightly", "evenly"], font: font, boldFont: boldFont) 

Swift 3.0

将html转换为string和字体根据您的要求更改。

 do { let str = try NSAttributedString(data: ("I'm a normal text and <b>this is my bold part . </b>And I'm again in the normal text".data(using: String.Encoding.unicode, allowLossyConversion: true)!), options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil) myLabel.attributedText = str myLabel.font = MONTSERRAT_BOLD(23) myLabel.textAlignment = NSTextAlignment.left } catch { print(error) } 

 func MONTSERRAT_BOLD(_ size: CGFloat) -> UIFont { return UIFont(name: "MONTSERRAT-BOLD", size: size)! } 

改善Prajeet Shrestha答案:

你可以为NSMutableAttributedString做一个通用的扩展,它涉及的代码较less。 在这种情况下,我select了使用系统字体,但是您可以使用它来input字体名称作为参数。

  extension NSMutableAttributedString { func systemFontWith(text: String, size: CGFloat, weight: CGFloat) -> NSMutableAttributedString { let attributes: [String: AnyObject] = [NSFontAttributeName: UIFont.systemFont(ofSize: size, weight: weight)] let string = NSMutableAttributedString(string: text, attributes: attributes) self.append(string) return self } }