NSAttributedString を受け取るメソッドを作成しました。文字列を入れるサブビューとラベルを動的に作成しようとしています。ラベルのサイズを正しく決定するには、フォントやサイズなどの属性を決定する必要があるため、属性付き文字列に適用された値と範囲を反復処理できるかどうかを決定する必要があります。
属性を個別に渡すことができることは理解していますが、再利用性のために、メソッドに渡すパラメーターをできるだけ少なくしたいと考えています。
NSAttributedString を受け取るメソッドを作成しました。文字列を入れるサブビューとラベルを動的に作成しようとしています。ラベルのサイズを正しく決定するには、フォントやサイズなどの属性を決定する必要があるため、属性付き文字列に適用された値と範囲を反復処理できるかどうかを決定する必要があります。
属性を個別に渡すことができることは理解していますが、再利用性のために、メソッドに渡すパラメーターをできるだけ少なくしたいと考えています。
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
ラベルを定義した場合。
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)
)
Apple のドキュメントには、属性にアクセスするためのメソッドがいくつかあります。
いずれかのタイプの属性付き文字列から属性値を取得するには、次のいずれかの方法を使用します。
attributesAtIndex:effectiveRange:
attributesAtIndex:longestEffectiveRange:inRange:
attribute:atIndex:effectiveRange:
attribute:atIndex:longestEffectiveRange:inRange:
fontAttributesInRange:
rulerAttributesInRange: