ios 在swift中使用属性字符串使文本加粗
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28496093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Making text bold using attributed string in swift
提问by user2413621
I have a string like this
我有一个这样的字符串
var str = "@text1 this is good @text1"
Now replace text1
with another string, say t 1
. I am able to replace the text, but i am not able to bold it. I want to bold the new string t 1
, so that the final output will be:
现在text1
用另一个字符串替换,比如t 1
。我可以替换文本,但无法将其加粗。我想加粗新字符串t 1
,以便最终输出:
@t 1this is good @t 1
@t 1这很好@t 1
How can I do it?
我该怎么做?
All the examples I am seeing are in Objective-C, but I want to do it in Swift.
我看到的所有示例都在 Objective-C 中,但我想在 Swift 中完成。
Thanks in advance.
提前致谢。
回答by Prajeet Shrestha
Usage:
用法:
let label = UILabel()
label.attributedText =
NSMutableAttributedString()
.bold("Address: ")
.normal(" Kathmandu, Nepal\n\n")
.orangeHighlight(" Email: ")
.blackHighlight(" [email protected] ")
.bold("\n\nCopyright: ")
.underlined(" All rights reserved. 2020.")
Result:
结果:
Here is a neat way to make a combination of bold and normal texts in a single label plus some other bonus methods.
这是在单个标签中组合粗体和普通文本以及其他一些奖励方法的巧妙方法。
Extension: Swift 5.*
扩展:Swift 5.*
extension NSMutableAttributedString {
var fontSize:CGFloat { return 14 }
var boldFont:UIFont { return UIFont(name: "AvenirNext-Bold", size: fontSize) ?? UIFont.boldSystemFont(ofSize: fontSize) }
var normalFont:UIFont { return UIFont(name: "AvenirNext-Regular", size: fontSize) ?? UIFont.systemFont(ofSize: fontSize)}
func bold(_ value:String) -> NSMutableAttributedString {
let attributes:[NSAttributedString.Key : Any] = [
.font : boldFont
]
self.append(NSAttributedString(string: value, attributes:attributes))
return self
}
func normal(_ value:String) -> NSMutableAttributedString {
let attributes:[NSAttributedString.Key : Any] = [
.font : normalFont,
]
self.append(NSAttributedString(string: value, attributes:attributes))
return self
}
/* Other styling methods */
func orangeHighlight(_ value:String) -> NSMutableAttributedString {
let attributes:[NSAttributedString.Key : Any] = [
.font : normalFont,
.foregroundColor : UIColor.white,
.backgroundColor : UIColor.orange
]
self.append(NSAttributedString(string: value, attributes:attributes))
return self
}
func blackHighlight(_ value:String) -> NSMutableAttributedString {
let attributes:[NSAttributedString.Key : Any] = [
.font : normalFont,
.foregroundColor : UIColor.white,
.backgroundColor : UIColor.black
]
self.append(NSAttributedString(string: value, attributes:attributes))
return self
}
func underlined(_ value:String) -> NSMutableAttributedString {
let attributes:[NSAttributedString.Key : Any] = [
.font : normalFont,
.underlineStyle : NSUnderlineStyle.single.rawValue
]
self.append(NSAttributedString(string: value, attributes:attributes))
return self
}
}
回答by Dejan Skledar
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.append(boldString)
When you want to assign it to a label:
当您想将其分配给标签时:
yourLabel.attributedText = attributedString
回答by Leo Dabus
edit/update: Xcode 8.3.2 ? Swift 3.1
编辑/更新:Xcode 8.3.2?斯威夫特 3.1
If you know HTML and CSS you can use it to easily control the font style, color and size of your attributed string as follow:
如果您了解 HTML 和 CSS,您可以使用它轻松控制属性字符串的字体样式、颜色和大小,如下所示:
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
回答by Ian
If you're working with localised strings, you might not be able to rely on the bold string always being at the end of the sentence. If this is the case then the following works well:
如果您使用本地化字符串,您可能无法依赖始终位于句子末尾的粗体字符串。如果是这种情况,那么以下方法运行良好:
e.g. Query "blah"does not match any items
例如查询“blah”不匹配任何项目
/* Create the search query part of the text, e.g. "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
回答by Jeremy Bader
I extended David West's great answer so that you can input a string and tell it allthe substrings you would like to embolden:
我扩展了大卫韦斯特的精彩答案,以便您可以输入一个字符串并告诉它您想要加强的所有子字符串:
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
}
And then call it like this:
然后像这样调用它:
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!)
This will embolden all the substrings you want bolded in your given string
这将使您想要在给定字符串中加粗的所有子字符串更加大胆
回答by Daniel McLean
Building on Jeremy Bader and David West's excellent answers, a Swift 3 extension:
基于 Jeremy Bader 和 David West 的出色回答,Swift 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
}
}
Usage:
用法:
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)
回答by David West
This is the best way that I have come up with. Add a function you can call from anywhere and add it to a file without a class like Constants.swift and then you can embolden words within any string, on numerous occasions by calling just ONE LINEof code:
这是我想出的最好的方法。添加一个您可以从任何地方调用的函数,并将其添加到一个没有像 Constants.swift 这样的类的文件中,然后您可以在任何字符串中添加单词,在很多情况下,只需调用一行代码:
To go in a constants.swift file:
进入一个 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
}
Then you can just call this one line of code for any UILabel:
然后你可以为任何 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)
回答by J.S.R - Silicornio
Accepting as valid the response of Prajeet Shresthain this thread, I would like to extend his solution using the Label if it is known and the traits of the font.
接受Prajeet Shrestha在此线程中的响应是有效的,如果已知 Label 和字体的特征,我想使用 Label 扩展他的解决方案。
Swift 4
斯威夫特 4
extension NSMutableAttributedString {
@discardableResult func normal(_ text: String) -> NSMutableAttributedString {
let normal = NSAttributedString(string: text)
append(normal)
return self
}
@discardableResult func bold(_ text: String, withLabel label: UILabel) -> NSMutableAttributedString {
//generate the bold font
var font: UIFont = UIFont(name: label.font.fontName , size: label.font.pointSize)!
font = UIFont(descriptor: font.fontDescriptor.withSymbolicTraits(.traitBold) ?? font.fontDescriptor, size: font.pointSize)
//generate attributes
let attrs: [NSAttributedStringKey: Any] = [NSAttributedStringKey.font: font]
let boldString = NSMutableAttributedString(string:text, attributes: attrs)
//append the attributed text
append(boldString)
return self
}
}
回答by Samuel
usage....
用法....
let attrString = NSMutableAttributedString()
.appendWith(weight: .semibold, "almost bold")
.appendWith(color: .white, weight: .bold, " white and bold")
.appendWith(color: .black, ofSize: 18.0, " big black")
two cents...
两分...
extension NSMutableAttributedString {
@discardableResult func appendWith(color: UIColor = UIColor.darkText, weight: UIFont.Weight = .regular, ofSize: CGFloat = 12.0, _ text: String) -> NSMutableAttributedString{
let attrText = NSAttributedString.makeWith(color: color, weight: weight, ofSize:ofSize, text)
self.append(attrText)
return self
}
}
extension NSAttributedString {
public static func makeWith(color: UIColor = UIColor.darkText, weight: UIFont.Weight = .regular, ofSize: CGFloat = 12.0, _ text: String) -> NSMutableAttributedString {
let attrs = [NSAttributedStringKey.font: UIFont.systemFont(ofSize: ofSize, weight: weight), NSAttributedStringKey.foregroundColor: color]
return NSMutableAttributedString(string: text, attributes:attrs)
}
}
回答by Ashish Chauhan
Super easy way to do this.
超级简单的方法来做到这一点。
let text = "This string is having multiple font"
let attributedText =
NSMutableAttributedString.getAttributedString(fromString: text)
attributedText.apply(font: UIFont.boldSystemFont(ofSize: 24), subString:
"This")
attributedText.apply(font: UIFont.boldSystemFont(ofSize: 24), onRange:
NSMakeRange(5, 6))
For more detail click here: https://github.com/iOSTechHub/AttributedString
有关更多详细信息,请单击此处:https: //github.com/iOSTechHub/AttributedString