ios 是否可以获得 NSMutableAttributedString 的属性和范围列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19844336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 02:49:01  来源:igfitidea点击:

Is it possible to get a listing of attributes and ranges for an NSMutableAttributedString?

iosuilabelnsattributedstringnsmutableattributedstring

提问by propstm

I've created a method that takes a NSAttributedString and I'm looking to dynamically create a subview and label to put the string into. Because attributes like font and size need to be determined to correctly determine the size of the label, I need to determine if it is possible to iterate through values and ranges that have been applied to the attributed string?

我创建了一个采用 NSAttributedString 的方法,我希望动态创建一个子视图和标签以将字符串放入。因为需要确定字体和大小等属性才能正确确定标签的大小,所以我需要确定是否可以遍历已应用于属性字符串的值和范围?

I understand that I could pass the attributes separately, but for sake of reusability, i'd like to be able to pass as few parameters to the method as possible.

我知道我可以单独传递属性,但为了可重用性,我希望能够将尽可能少的参数传递给方法。

采纳答案by Tommy

Apple expects you to use enumerateAttributesInRange:options:usingBlock:. The block you supply will receive ranges and the attributes applicable for that range.

Apple 希望您使用enumerateAttributesInRange:options:usingBlock:. 您提供的块将接收范围和适用于该范围的属性。

I've used that in my code to create invisible buttons that are placed behind text so that it acts as a hyperlink.

我在我的代码中使用它来创建放置在文本后面的不可见按钮,以便它充当超链接。

You could also use enumerateAttribute:inRange:options:usingBlock:if there's only one you're interested in, but no halfway house is provided where you might be interested in, say, two attributes but not every attribute.

你也可以使用enumerateAttribute:inRange:options:usingBlock:,如果有只有你感兴趣的一个,但是没有提供中途之家,你可能会感兴趣的,比如说,两个属性但不是每个属性。

回答by dimpiax

Swift 5 – 4

斯威夫特 5 – 4

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)
}


In case, that you have defined attributedTextof label.

如果您已经定义attributedText了标签。

Swift 3

斯威夫特 3

var attributes = attributedText.attributes(
  at: 0, 
  longestEffectiveRange: nil, 
  in: NSRange(location: 0, length: attributedText.length))

Swift 2.2

斯威夫特 2.2

var attributes = attributedText.attributesAtIndex(0,   
  longestEffectiveRange: nil, 
  inRange: NSMakeRange(0, attributedText.length))

回答by TheJeff

If you need all of the attributes from the string in the entire range, use this code:

如果您需要整个范围内字符串的所有属性,请使用以下代码:

NSDictionary *attributesFromString = [stringWithAttributes attributesAtIndex:0 longestEffectiveRange:nil inRange:NSMakeRange(0, stringWithAttributes.length)];

NSDictionary *attributesFromString = [stringWithAttributes attributesAtIndex:0 longestEffectiveRange:nil inRange:NSMakeRange(0, stringWithAttributes.length)];

回答by Trein

Swift 3:

斯威夫特 3:

// in case, that you have defined `attributedText` of label
var attributes = attributedText.attributes(at: 0, longestEffectiveRange: nil, in: NSMakeRange(0, attributedText.length))
...

回答by paulrehkugler

Apple's Docshave a number of methods to access attributes:

Apple 的 Docs有许多访问属性的方法:

To retrieve attribute values from either type of attributed string, use any of these methods:

要从任一类型的属性字符串中检索属性值,请使用以下任一方法:

attributesAtIndex:effectiveRange:attributesAtIndex:longestEffectiveRange:inRange:attribute:atIndex:effectiveRange:attribute:atIndex:longestEffectiveRange:inRange:fontAttributesInRange:rulerAttributesInRange:

attributesAtIndex:effectiveRange:attributesAtIndex:longestEffectiveRange:inRange:attribute:atIndex:effectiveRange:attribute:atIndex:longestEffectiveRange:inRange:fontAttributesInRange:rulerAttributesInRange:

回答by Josh O'Connor

Swift 4:

斯威夫特 4:

If you want to get the attributes for NSTextAttachment (just change the attribute value if you want font)

如果你想获取 NSTextAttachment 的属性(如果你想要字体,只需更改属性值)

commentTextView.attributedText.enumerateAttribute(NSAttachmentAttributeName,
                        in:NSMakeRange(0, commentTextView.attributedText.length),
                        options:.longestEffectiveRangeNotRequired) {
                        value, range, stop in
                            if let attachment = value as? NSTextAttachment {
                                print("GOT AN ATTACHMENT! for comment at \(indexPath.row)")
                            }
}

回答by Micha? Ziobro

I have modified one of the answers with suggested fixes to prevent infinite recursion and application crashes.

我已经用建议的修复程序修改了其中一个答案,以防止无限递归和应用程序崩溃。

@IBDesignable
extension UITextField{

    @IBInspectable var placeHolderColor: UIColor? {
        get {
            if let color = self.attributedPlaceholder?.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? UIColor {
                return color
            }
            return nil
        }
        set {
            self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[.foregroundColor: newValue!])
        }
    }
}