[英]How to replace string in NSMutableAttributedString?
I have this : 我有这个 :
var attributedString = NSMutableAttributedString(string:"Welcome %@ to %@")
And I want to format this to add some other NSMutableAttributedString
instead of %@
我想格式化它以添加其他一些NSMutableAttributedString
而不是%@
How can I achieve that? 我该如何实现?
Thanks 谢谢
You can replace NSAttributeString
with another NSAttributeString
by following way. 您可以通过以下方式将NSAttributeString
替换为另一个NSAttributeString
。 here in this example, you need to fine location of %@
symbol. 在此示例中,您需要精确定位%@
符号。
let stringVariable = "Welcome @ location"
var attributedString = NSMutableAttributedString(string:stringVariable)
var attributedStringAnother = NSMutableAttributedString(string:"abc")
attributedString.replaceCharactersInRange(NSRange(location: 8,length: 1), withAttributedString: attributedStringAnother)
println(attributedString)
Here location: 8
is a location @
symbol. 此处的location: 8
是位置@
符号。
Output is : 输出为:
Welcome abc location{
}
Hope this help you. 希望这对您有所帮助。
Try this: 尝试这个:
var attributedString = NSMutableAttributedString(string:"Welcome %@ to %@")
let result = attributedString.string.stringByReplacingOccurrencesOfString("%@", withString:"TEST")
var newAtrString = NSMutableAttributedString(string: result)
在Swift中,您可以这样操作:
var attributedString = NSMutableAttributedString(string:"Welcome \\(anotherAttributedString1) to \\(anotherAttributedString2)")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.