pro*_*stm 43 nsattributedstring uilabel ios nsmutableattributedstring
我创建了一个采用NSAttributedString的方法,我正在寻找动态创建子视图和标签以将字符串放入.因为需要确定字体和大小等属性来正确确定标签的大小,我需要确定是否可以迭代已应用于属性字符串的值和范围?
我知道我可以单独传递属性,但为了可重用性,我希望能够尽可能少地将参数传递给方法.
dim*_*iax 65
let attributedText = NSAttributedString(string: "Hello, playground", attributes: [
.foregroundColor: UIColor.red,
.backgroundColor: UIColor.green,
.ligature: 1,
.strikethroughStyle: 1
])
// retrieve attributes
let attributes = attributedText.attributes(at: 0, effectiveRange: nil)
// iterate each attribute
for attr in attributes {
print(attr.key, attr.value)
}
Run Code Online (Sandbox Code Playgroud)
如果您已定义attributedText
标签.
var attributes = attributedText.attributes(
at: 0,
longestEffectiveRange: nil,
in: NSRange(location: 0, length: attributedText.length))
Run Code Online (Sandbox Code Playgroud)
Swift 2.2
var attributes = attributedText.attributesAtIndex(0,
longestEffectiveRange: nil,
inRange: NSMakeRange(0, attributedText.length))
Run Code Online (Sandbox Code Playgroud)
Tom*_*mmy 22
Apple希望您使用enumerateAttributesInRange:options:usingBlock:
.您提供的块将接收范围和适用于该范围的属性.
我在我的代码中使用它来创建隐藏在文本后面的隐藏按钮,以便它充当超链接.
你也可以使用,enumerateAttribute:inRange:options:usingBlock:
如果只有你感兴趣的那个,但没有提供你可能感兴趣的中途房子,比如两个属性,但不是每个属性.
The*_*eff 11
如果您需要整个范围内字符串的所有属性,请使用以下代码:
NSDictionary *attributesFromString = [stringWithAttributes attributesAtIndex:0 longestEffectiveRange:nil inRange:NSMakeRange(0, stringWithAttributes.length)];