쪼렙 as! 풀스택

Swift - UILabel 에 부분적으로 Bold 처리한 텍스트 입력하기. 17.11.21. 본문

개발 일지/iOS & Android

Swift - UILabel 에 부분적으로 Bold 처리한 텍스트 입력하기. 17.11.21.

코코앱 2017. 11. 21. 17:50

UILabel 에 부분적으로 Bold 처리하고 싶을 때가 많이 있다.


AttributedString 을 쓰면 되는데,

이게 매번 쓰기가 참 귀찮다.


그래서,편하게 "Bold" 스타일과, "Normal" 스타일을 번갈아가면서, 마음대로 Attributed String 을 만드는 Extension 을 만들어서 간단히 해결.


extension NSMutableAttributedString {

    func bold(_ text: String, fontSize: CGFloat) -> NSMutableAttributedString {

        let attrs: [NSAttributedStringKey: Any] = [.font: UIFont.boldSystemFont(ofSize: fontSize)]

        self.append(NSMutableAttributedString(string: text, attributes: attrs))

        return self

    }

    

    func normal(_ text: String, fontSize: CGFloat) -> NSMutableAttributedString {

        let attrs: [NSAttributedStringKey: Any] = [.font: UIFont.systemFont(ofSize: fontSize)]

        self.append(NSMutableAttributedString(string: text, attributes: attrs))

        return self

    }

}




사용하기.

let attributedString = NSMutableAttributedString()

    .bold("두꺼운 문자열", fontSize: 15)

    .normal("보통 문자열", fontSize: 15)


uiLabel.attributedText = attrString;


Comments