카테고리 없음

swift 라벨에 텍스트 색상 따로 지정해보기

kingarthur 2024. 8. 23. 21:07

오랜만에 글을 적는거 같다. 

이유는 오랜만에 개발을 해서??

 

아무튼 오늘 개발을 하다가 텍스트마다 색상을 따로 주고 싶었는데 한번도 안해봐서 

새롭게 써보게되어서 적게되었다. 

 

    let introLabel: UILabel = {
        let introLabel = UILabel()
        introLabel.translatesAutoresizingMaskIntoConstraints = false
        let fullText = "300s"
        let range = (fullText as NSString).range(of: "s")
        let attributedString = NSMutableAttributedString(string: fullText)
        attributedString.addAttribute( .foregroundColor, value: UIColor.white, range: NSRange(location: 0, length: fullText.count))
        attributedString.addAttribute(.font, value: UIFont.boldSystemFont(ofSize: 40), range: NSRange(location: 0, length: fullText.count))
        attributedString.addAttribute(.foregroundColor, value: UIColor.red, range: range)
        introLabel.attributedText = attributedString
        introLabel.textAlignment = .center
        return introLabel
    }()

 

이렇게 작성하면 된다 앞으로 자주 사용해봐야겠다