Unknown Region

プログラムでハマったエラーとその解決方法についての備忘録メモ

【Swift4】UILabelにおいて、色を付けたAttributedTextの設定後にUILabel.textColorをするとUILabel.textColorが優先される

ハマったのでメモ。

let text: String = "hogehoge"
let attributedText: NSMutableAttributedString = NSMutableAttributedString(string: text)
attributedText.addAttribute(.foregroundColor, value: UIColor.red, range: NSMakeRange(0, text.count))
let label: UILabel = UILabel(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 100.0, height: 100.0)))
label.attributedText = attributedText
label.textColor = UIColor.black

こうすると、attributedTextの設定(文字色が赤)が無視されて全部textColorの設定(文字色が黒)になる

let text: String = "hogehoge"
let attributedText: NSMutableAttributedString = NSMutableAttributedString(string: text)
attributedText.addAttribute(.foregroundColor, value: UIColor.red, range: NSMakeRange(0, text.count))
let label: UILabel = UILabel(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 100.0, height: 100.0)))
label.textColor = UIColor.black
label.attributedText = attributedText

textColorを設定してからattributedTextを設定してやれば、ちゃんと動く(文字が赤になる)

 

連絡先: plugout777★yahoo.co.jp (クローラー対策のため★を@に変更してください)