65

NSAttributedString を受け取るメソッドを作成しました。文字列を入れるサブビューとラベルを動的に作成しようとしています。ラベルのサイズを正しく決定するには、フォントやサイズなどの属性を決定する必要があるため、属性付き文字列に適用された値と範囲を反復処理できるかどうかを決定する必要があります。

属性を個別に渡すことができることは理解していますが、再利用性のために、メソッドに渡すパラメーターをできるだけ少なくしたいと考えています。

4

7 に答える 7

98

スイフト 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)
}

attributedTextラベルを定義した場合。

スイフト3

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

スイフト 2.2

var attributes = attributedText.attributesAtIndex(0,   
  longestEffectiveRange: nil, 
  inRange: NSMakeRange(0, attributedText.length)
)
于 2016-07-10T23:46:06.163 に答える
3

Apple のドキュメントには、属性にアクセスするためのメソッドがいくつかあります。

いずれかのタイプの属性付き文字列から属性値を取得するには、次のいずれかの方法を使用します。

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

于 2013-11-07T19:07:32.683 に答える