本文介绍了如何使用Swift创建一个属性字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我已经通过搜索一个属性字符串的文档,我甚至从应用商店下了一个Attributed String Creator,但是结果代码是在Objective-C中,我正在使用Swift。对于学习这种语言的其他开发者来说,什么是可怕的,并且可能是有帮助的,这是一个使用Swift中的属性字符串创建具有自定义属性的自定义字体的明显例子。这方面的文件非常混乱,因为在这方面没有一个非常清晰的路径。我的计划是创建属性字符串,并将其添加到我的coffeeAmount字符串的末尾。

pre $ var cAmount:String = calculatedCoffee +其中calculateCoffee是一个Int转换为一个字符串,JavasText是小写的g与自定义的字体,我试图创建。也许我正在做这个错误的方式。任何帮助表示赞赏!

解决方案


这个答案已经为Swift 4.0更新了。

快速参考



制作和设置属性字符串的一般形式是这样的。

  //创建归属字符串
let myString =Swift Attributed String
let myAttribute = [NSAttributedStringKey.foregroundColor:UIColor.blue]
let myAttrString = NSAttributedString(string:myString,attributes:myAttribute)

//在UILabel上设置属性文本
myLabel.attributedText = myAttrString
  let myAttribute = [NSAttributedStringKey.foregroundColor:UIColor.blue] 
  let myAttribute = [NSAttributedStringKey.font:UIFont(name:Chalkduster,size:18.0)! ] 
  let myAttribute = [NSAttributedStringKey.underlineStyle:NSUnderlineStyle.styleSingle.rawValue] 
  let myShadow = NSShadow()
myShadow.shadowBlurRadius = 3
myShadow.shadowOffset = CGSize(width:3,height:3)
myShadow.shadowColor = UIColor.gray

let myAttribute = [NSAttributedStringKey .shadow:myShadow]

这篇文章的其余部分给了那些感兴趣的人更多的细节。 p>




属性



字符串属性只是字典形式 [NSAttributedStri ngKey:Any] ,其中 NSAttributedStringKey 是属性的键名, Any 是某些类型的值。值可以是字体,颜色,整数或其他。 Swift中有很多已经预定义的标准属性。例如:


  • 键名: NSAttributedStringKey.font ,值:a UIFont

  • 键名: NSAttributedStringKey.foregroundColor ,值:a UIColor

  • 键名: NSAttributedStringKey.link ,值: NSURL 字符串



。有关更多信息,请参阅

然后附加另一个属性字符串,没有任何属性设置。 (请注意,即使我使用来声明 myString ,我仍然可以修改它,因为它是 NSMutableAttributedString 。这对我来说似乎并不太令人满意,如果将来发生变化,我也不会感到惊讶,如果发生这种情况,请留下我的评论。)

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


接下来,我们将选择字符串字,从索引 17 开始,长度为 7 。请注意,这是 NSRange 而不是Swift Range 。 (有关范围的更多信息,请参阅



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

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


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



相关




  • /developer.apple.com/library/ios/documentation/Cocoa/Conceptual/AttributedStrings/AttributedStrings.htmlrel =noreferrer>赋值字符串编程指南(非常翔实,但不幸的是只在Objective-C中) li>

I am trying to make a simple Coffee Calculator. I need to display the amount of coffee in grams. The "g" symbol for grams needs to be attached to my UILabel that I am using to display the amount. The numbers in the UILabel are changing dynamically with user input just fine, but I need to add a lower case "g" on the end of the string that is formatted differently from the updating numbers. The "g" needs to be attached to the numbers so that as the number size and position changes, the "g" "moves" with the numbers. I'm sure this problem has been solved before so a link in the right direction would be helpful as I've googled my little heart out.

I've searched through the documentation for an attributed string and I even downloded an "Attributed String Creator" from the app store, but the resulting code is in Objective-C and I am using Swift. What would be awesome, and probably helpful to other developers learning this language, is a clear example of creating a custom font with custom attributes using an attributed string in Swift. The documentation for this is very confusing as there is not a very clear path on how to do so. My plan is to create the attributed string and add it to the end of my coffeeAmount string.

var coffeeAmount: String = calculatedCoffee + attributedText

Where calculatedCoffee is an Int converted to a string and "attributedText" is the lowercase "g" with customized font that I am trying to create. Maybe I'm going about this the wrong way. Any help is appreciated!

解决方案

This answer has been updated for Swift 4.0.

Quick Reference

The general form for making and setting an attributed string is like this. You can find other common options below.

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

// set attributed text on a UILabel
myLabel.attributedText = myAttrString
let myAttribute = [ NSAttributedStringKey.foregroundColor: UIColor.blue ]
let myAttribute = [ NSAttributedStringKey.backgroundColor: UIColor.yellow ]
let myAttribute = [ NSAttributedStringKey.font: UIFont(name: "Chalkduster", size: 18.0)! ]
let myAttribute = [ NSAttributedStringKey.underlineStyle: NSUnderlineStyle.styleSingle.rawValue ]
let myShadow = NSShadow()
myShadow.shadowBlurRadius = 3
myShadow.shadowOffset = CGSize(width: 3, height: 3)
myShadow.shadowColor = UIColor.gray

let myAttribute = [ NSAttributedStringKey.shadow: myShadow ]

The rest of this post gives more detail for those who are interested.


Attributes

String attributes are just a dictionary in the form of [NSAttributedStringKey: Any], where NSAttributedStringKey is the key name of the attribute and Any is the value of some Type. The value could be a font, a color, an integer, or something else. There are many standard attributes in Swift that have already been predefined. For example:

  • key name: NSAttributedStringKey.font, value: a UIFont
  • key name: NSAttributedStringKey.foregroundColor, value: a UIColor
  • key name: NSAttributedStringKey.link, value: an NSURL or String

There are many others. See this link for more. You can even make your own custom attributes like:

  • key name: NSAttributedStringKey.myName, value: some Type.
    if you make an extension:

    extension NSAttributedStringKey {
        static let myName = NSAttributedStringKey(rawValue: "myCustomAttributeKey")
    }
    

Creating attributes in Swift

You can declare attributes just like declaring any other dictionary.

// single attributes declared one at a time
let singleAttribute1 = [ NSAttributedStringKey.foregroundColor: UIColor.green ]
let singleAttribute2 = [ NSAttributedStringKey.backgroundColor: UIColor.yellow ]
let singleAttribute3 = [ NSAttributedStringKey.underlineStyle: NSUnderlineStyle.styleDouble.rawValue ]

// multiple attributes declared at once
let multipleAttributes: [NSAttributedStringKey : Any] = [
    NSAttributedStringKey.foregroundColor: UIColor.green,
    NSAttributedStringKey.backgroundColor: UIColor.yellow,
    NSAttributedStringKey.underlineStyle: NSUnderlineStyle.styleDouble.rawValue ]

// custom attribute
let customAttribute = [ NSAttributedStringKey.myName: "Some value" ]

Note the rawValue that was needed for the underline style value.

Because attributes are just Dictionaries, you can also create them by making an empty Dictionary and then adding key-value pairs to it. If the value will contain multiple types, then you have to use Any as the type. Here is the multipleAttributes example from above, recreated in this fashion:

var multipleAttributes = [NSAttributedStringKey : Any]()
multipleAttributes[NSAttributedStringKey.foregroundColor] = UIColor.green
multipleAttributes[NSAttributedStringKey.backgroundColor] = UIColor.yellow
multipleAttributes[NSAttributedStringKey.underlineStyle] = NSUnderlineStyle.styleDouble.rawValue

Attributed Strings

Now that you understand attributes, you can make attributed strings.

Initialization

There are a few ways to create attributed strings. If you just need a read-only string you can use NSAttributedString. Here are some ways to initialize it:

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

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

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

If you will need to change the attributes or the string content later, you should use NSMutableAttributedString. The declarations are very similar:

// 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: [NSAttributedStringKey.myName: "A value"])

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

Changing an Attributed String

As an example, let's create the attributed string at the top of this post.

First create an NSMutableAttributedString with a new font attribute.

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

If you are working along, set the attributed string to a UITextView (or UILabel) like this:

textView.attributedText = myString

You don't use textView.text.

Here is the result:

Then append another attributed string that doesn't have any attributes set. (Notice that even though I used let to declare myString above, I can still modify it because it is an NSMutableAttributedString. This seems rather unSwiftlike to me and I wouldn't be surprised if this changes in the future. Leave me a comment when that happens.)

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

Next we'll just select the "Strings" word, which starts at index 17 and has a length of 7. Notice that this is an NSRange and not a Swift Range. (See this answer for more about Ranges.) The addAttribute method lets us put the attribute key name in the first spot, the attribute value in the second spot, and the range in the third spot.

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

Finally, let's add a background color. For variety, let's use the addAttributes method (note the s). I could add multiple attributes at once with this method, but I will just add one again.

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

Notice that the attributes are overlapping in some places. Adding an attribute doesn't overwrite an attribute that is already there.

Related

Further Reading

这篇关于如何使用Swift创建一个属性字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-03 03:03
查看更多