字体 – 如何使用Swift属性字符串?

我试图做一个简单的咖啡计算器。我需要显示咖啡的克数。克的“g”符号需要附加到我用来显示金额的UILabel。 UILabel中的数字正在随着用户输入动态改变,但我需要在字符串的末尾添加一个小写字母“g”,格式与更新的数字不同。 “g”需要附加到数字,以便随着数字大小和位置的变化,“g”随数字移动。我相信这个问题已经解决之前,所以一个正确的方向的链接将有所帮助,因为我已经搜索我的小心脏。

搜索一个属性字符串的文档,我甚至下载了一个“Attributed String Creator”从应用商店,但最终的代码是在Objective-C,我使用的是Swift。什么是真棒,并且可能有助于其他开发人员学习这种语言,是一个清晰的例子使用在Swift中的属性字符串创建自定义字体与自定义属性。这个文档非常混乱,因为没有一个非常清楚的路径如何做。我的计划是创建属性字符串并将其添加到我的coffeeAmount字符串的末尾。

var coffeeAmount: String = calculatedCoffee + attributedText

其中computedCoffee是一个转换为字符串的Int,“attributedText”是我尝试创建的自定义字体的小写“g”。也许我要这个错误的方式。任何帮助是赞赏!

这个答案已更新为Swift 3.0。

快速参考

创建和设置属性字符串的一般形式是这样的。您可以在下面找到其他常见选项。

// create attributed string
let myString = "Swift Attributed String"
let myAttribute = [ NSForegroundColorAttributeName: UIColor.blue ]
let myAttrString = NSAttributedString(string: myString,attributes: myAttribute) 

// set attributed text on a UILabel
myLabel.attributedText = myAttrString

let myAttribute = [ NSForegroundColorAttributeName: UIColor.blue ]

let myAttribute = [ NSBackgroundColorAttributeName: UIColor.yellow ]

let myAttribute = [ NSFontAttributeName: UIFont(name: "Chalkduster",size: 18.0)! ]

let myAttribute = [ NSUnderlinestyleAttributeName: NSUnderlinestyle.StyleSingle.rawValue ]

let myShadow = NSShadow()
myShadow.shadowBlurRadius = 3
myShadow.shadowOffset = CGSize(width: 3,height: 3)
myShadow.shadowColor = UIColor.gray

let myAttribute = [ NSShadowAttributeName: myShadow ]

这篇文章的其余部分给了更多的细节,有兴趣的人。

属性

String属性只是一个[String:Any]形式的字典,其中String是属性的键名称,Any是某些Type的值。该值可以是字体,颜色,整数或其他。 Swift中有许多已经预定义的标准属性。例如:

>键名:NSFontAttributeName,value:a UIFont
>键名:NSForegroundColorAttributeName,value:a UIColor
>键名称:NSLinkAttributeName,value:NSURL或String

还有很多其他的。更多信息参见this link。您甚至可以创建自己的自定义属性

>键名:MyCustomAttributeName,value:some类型。

在Swift中创建属性

你可以像声明任何其他字典一样声明属性

// single attributes declared one at a time
let singleAttribute1 = [ NSForegroundColorAttributeName: UIColor.green ]
let singleAttribute2 = [ NSBackgroundColorAttributeName: UIColor.yellow ]
let singleAttribute3 = [ NSUnderlinestyleAttributeName: NSUnderlinestyle.styleDouble.rawValue ]

// multiple attributes declared at once
let multipleAttributes: [String : Any] = [
    NSForegroundColorAttributeName: UIColor.green,NSBackgroundColorAttributeName: UIColor.yellow,NSUnderlinestyleAttributeName: NSUnderlinestyle.styleDouble.rawValue ]

// custom attribute
let customAttribute = [ "MyCustomAttributeName": "Some value" ]

注意下划线样式值所需的rawValue。

因为属性只是字典,您还可以通过创建一个空的字典然后向其中添加键值对来创建它们。如果值包含多个类型,那么您必须使用Any作为类型。这里是从上面的multipleAttributes示例,以这种方式重新创建:

var multipleAttributes = [String : Any]()
multipleAttributes[NSForegroundColorAttributeName] = UIColor.green
multipleAttributes[NSBackgroundColorAttributeName] = UIColor.yellow
multipleAttributes[NSUnderlinestyleAttributeName] = NSUnderlinestyle.styleDouble.rawValue

属性字符串

现在你理解属性,你可以使属性字符串。

初始化

有几种方法来创建属性字符串。如果你只需要一个只读字符串,你可以使用NSAttributedString。这里有一些方法来初始化它:

// Initialize with a string only
let attrString1 = NSAttributedString(string: "Hello.")

// Initialize with a string and inline attribute(s)
let attrString2 = NSAttributedString(string: "Hello.",attributes: ["MyCustomAttribute": "A value"])

// Initialize with a string and separately declared attribute(s)
let myAttributes1 = [ NSForegroundColorAttributeName: UIColor.green ]
let attrString3 = NSAttributedString(string: "Hello.",attributes: myAttributes1)

如果以后需要更改属性或字符串内容,则应使用NSMutableAttributedString。声明非常相似:

// Create a blank attributed string
let mutableAttrString1 = NSMutableAttributedString()

// Initialize with a string only
let mutableAttrString2 = NSMutableAttributedString(string: "Hello.")

// Initialize with a string and inline attribute(s)
let mutableAttrString3 = NSMutableAttributedString(string: "Hello.",attributes: ["MyCustomAttribute": "A value"])

// Initialize with a string and separately declared attribute(s)
let myAttributes2 = [ NSForegroundColorAttributeName: UIColor.green ]
let mutableAttrString4 = NSMutableAttributedString(string: "Hello.",attributes: myAttributes2)

更改属性字符串

例如,让我们在此帖的顶部创建属性字符串。

首先创建一个带有新字体属性的NSMutableAttributedString。

let myAttribute = [ NSFontAttributeName: UIFont(name: "Chalkduster",size: 18.0)! ]
let myString = NSMutableAttributedString(string: "Swift",attributes: myAttribute )

如果你正在努力,将属性字符串设置为UITextView(或UILabel),如下所示:

textView.attributedText = myString

您不使用textView.text。

这里是结果:

然后附加没有设置任何属性的另一个属性字符串。 (请注意,即使我使用let声明myString上面,我仍然可以修改它,因为它是一个NSMutableAttributedString。这似乎相当unSwiftlike我和我不会感到惊讶,如果这种变化在未来。发生。)

let attrString = NSAttributedString(string: " Attributed Strings")
myString.append(attrString)

接下来,我们只选择“Strings”字,它从索引17开始,长度为7.注意这是一个NSRange而不是一个Swift范围。 (有关范围的更多信息,请参阅this answer.)addAttribute方法允许我们将属性名称放在第一个位置,属性值放在第二个位置,将范围放在第三个位置。

var myRange = NSRange(location: 17,length: 7) // range starting at location 17 with a lenth of 7: "Strings"
myString.addAttribute(NSForegroundColorAttributeName,value: UIColor.red,range: myRange)

最后,让我们添加一个背景颜色。对于多样性,让我们使用addAttributes方法(注意s)。我可以用这个方法一次添加多个属性,但我只是再添加一个

myRange = NSRange(location: 3,length: 17)
let anotherAttribute = [ NSBackgroundColorAttributeName: UIColor.yellow ]
myString.addAttributes(anotherAttribute,range: myRange)

请注意,属性在某些地方重叠。添加属性不会覆盖已经存在的属性

有关

> How to change the text of an NSMutableAttributedString but keep the attributes

进一步阅读

> How to retrieve the attributes from a tap location
> Attributed String Programming Guide(非常信息,但不幸的是只有在Objective-C)

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...