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

前端 未结 7 1328
小蘑菇
小蘑菇 2021-02-01 12:36

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 n

7条回答
  •  悲哀的现实
    2021-02-01 13:07

    Swift 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 attributedText of label.

    Swift 3

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

    Swift 2.2

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

提交回复
热议问题