use*_*906 15 nsattributedstring ios
刚开始swift 3我遇到了快速语法问题.
我想要显示一个简单的NSAttributedString.
所以我先设定我的属性:
let attributeFontSaySomething : [String : AnyObject] = [NSFontAttributeName : UIFont.fontSaySomething()]
let attributeColorSaySomething : [String : AnyObject] = [NSForegroundColorAttributeName : UIColor.blue]
Run Code Online (Sandbox Code Playgroud)
然后我创建我的字符串:
let attStringSaySomething = NSAttributedString(string: "Say something", attributes: self.attributeFontSaySomething)
Run Code Online (Sandbox Code Playgroud)
我想要做的是创建具有我的2个属性的字符串,而不仅仅是一个.但当我这样做时:
let attStringSaySomething = NSAttributedString(string: "Say something", attributes: [self.attributeFontSaySomething, self.attributeColorSaySomething])
Run Code Online (Sandbox Code Playgroud)
Xcode告诉我,我不能并希望我为字典词典更改此内容.
如何在不使用NSMutableAttributedString?的情况下使用2个属性创建字符串?
vad*_*ian 25
主要问题是您传递的是数组 [attr.. , attr...]而不是一个字典.
您需要将两个词典合并为一个
let attributeFontSaySomething : [String : Any] = [NSFontAttributeName : UIFont.systemFont(ofSize: 12.0)]
let attributeColorSaySomething : [String : Any] = [NSForegroundColorAttributeName : UIColor.blue]
var attributes = attributeFontSaySomething
for (key, value) in attributeColorSaySomething {
attributes(value, forKey: key)
}
let attStringSaySomething = NSAttributedString(string: "Say something", attributes: attributes)
Run Code Online (Sandbox Code Playgroud)
但是,按字面意思创建字典可能更容易:
let attributes : [String : Any] = [NSFontAttributeName : UIFont.systemFont(ofSize: 12.0), NSForegroundColorAttributeName : UIColor.blue]
Run Code Online (Sandbox Code Playgroud)
只需使用两组属性创建一个字典:
let attributes: [String:AnyObject] =
[NSFontAttributeName : UIFont.fontSaySomething(),
NSForegroundColorAttributeName : UIColor.blue]
Run Code Online (Sandbox Code Playgroud)
然后在创建属性字符串时使用包含键/值对的字典.
Swift中没有用于组合字典的内置机制,但+如果您希望能够一起添加字典,则可以添加操作符的覆盖(如果两个字典包含相同的键,则必须确定要做什么.)
| 归档时间: |
|
| 查看次数: |
25177 次 |
| 最近记录: |