NSAttributedString 연속 사용

피터·2022년 10월 25일
0

NSAttributedString을 편하게 사용하고
가운데 정렬과 text line 간의 height까지 적용할 수 있는 메서드입니다~!

소스코드

extension NSMutableAttributedString {
    
    func attributeString(string: String, font: UIFont?, textColor: UIColor, lineSpace: CGFloat? = nil, isCenter: Bool = false) -> NSMutableAttributedString {
        var attributes: [NSAttributedString.Key: Any] = [
            .font: font ?? UIFont.boldSystemFont(ofSize: 16),
            .foregroundColor: textColor
        ]
        
        let paragraphStyle = NSMutableParagraphStyle()
		
        // 텍스트 line 간의 height 설정
        if let lineSpace = lineSpace {
            paragraphStyle.lineSpacing = lineSpace
        }
        
        // 텍스트의 가운데 정렬
        if isCenter {
            paragraphStyle.alignment = .center
        }

        attributes[.paragraphStyle] = paragraphStyle

        self.append(NSAttributedString(string: string, attributes: attributes))
        
        return self
    }
}

사용 예시

NSMutableAttributedString()
            .attributeString(
                string: "일주일 동안\n",
                font: .systemFont(ofSize: 18, weight: .bold),
                textColor: .black,
                lineSpace: 10,
                isCenter: true
            )
            .attributeString(
                string: "총 ",
                font: .systemFont(ofSize: 18, weight: .bold),
                textColor: .black,
                isCenter: true
            )
            .attributeString(
                string: "4000 걸음",
                font: .systemFont(ofSize: 40, weight: .bold),
                textColor: .blue,
                isCenter: true
            )
            .attributeString(
                string: " 을 걸었어요!",
                font: .systemFont(ofSize: 18, weight: .bold),
                textColor: .black,
                isCenter: true
            )

결과물

profile
iOS 개발자입니다.

0개의 댓글