将字体大小和自定义字体名称添加到UITextView中的属性字符串
问题描述:
我有以下代码将属性字符串添加到UITextView文本。我需要在swift中添加自定义字体和字体大小。怎么做?将字体大小和自定义字体名称添加到UITextView中的属性字符串
func setAttributedString(string: String) -> NSAttributedString {
let attrString = NSMutableAttributedString(string: string)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 7
paragraphStyle.minimumLineHeight = 7
attrString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSRange(location: 0, length:attrString.length))
attrString.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 30), range: NSRange(location: 0, length:attrString.length))
return attrString
}
我需要将自定义字体和字体大小添加到以下函数。如何实现这一目标?
答
swift3
设属性= [NSAttributedStringKey.font:UIFont(名: “HelveticaNeue-粗体”,大小:17)! NSAttributedStringKey.foregroundColor:UIColor.white]
让attributedString = NSMutableAttributedString (字符串: “你的字符串”,属性:属性)
答
使用初始化的init(字符串:属性:)
https://developer.apple.com/documentation/foundation/nsattributedstring/1408136-init
let attrString = NSMutableAttributedString(string: string, attributes:
[NSFontAttributeName:UIFont(
name: "Georgia",
size: 18.0)!])
//Add more attributes here
可能重复[如何使用Swift创建属性字符串?](https://stackoverflow.com/questions/24666515/how-do-i-make-an-attributed-string-using-swift ) –
你会希望从链接得到你的答案。只需将语法转换为最新的swift语法即可。 –
https://stackoverflow.com/questions/46460034/swift-3-render-textview-using-nsattributedstring-but-want-change-the-default-fon/46460119#46460119 –