개발/아이오에스

swift] attributedText으로 텍스트마다 다양한 스타일(폰트,사이즈,색상), NSMutableParagraphStyle으로 텍스트사이 간격주기

dev.jake 2021. 3. 4. 14:00

messageTextView.attributedText = attributedText
위 사진처럼 messageTextView에  attributedText을 통해

총 3가지의 폰트를 설정해줬습니다.

let attributedText = NSMutableAttributedString(string: tweet.user.name, attributes: [NSAttributedString.Key.font:UIFont.boldSystemFont(ofSize: 16)])
let usernameString = "  \(tweet.user.username)\n"
            attributedText.append(NSAttributedString(string: usernameString, attributes: [NSAttributedString.Key.font:UIFont.systemFont(ofSize: 15),NSAttributedString.Key.foregroundColor: UIColor.gray]))
 attributedText.append(NSAttributedString(string: tweet.message, attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 15)]))
            messageTextView.attributedText = attributedText

 

 

let attributedText = NSMutableAttributedString( string : , attributes: [NSAtttributedString.Key.font : UIFont.boldSystemFont(ofSize:16)]) 이렇게 NSMutableAttributedString을 사용해서 문자열값, 문자열의 폰트를 설정해줬습니다.

선언한 attributedText는 이제 입력할 messageTextView에 messageTextView.attributedText = attributedText 이런식으로 사용이 됩니다.

 

선언한 attributedText에 이제 append를 통해 또 다른 텍스트(스타일)을 추가해줍니다.

attributedText.append(NSAttributedString(string: usernameString, attributes: [NSAttributedString.Key.font:UIFont.systemFont(ofSize: 15),NSAttributedString.Key.foregroundColor: UIColor.gray]))

두 번째 문자열은 NSAttributedString.Key.foregroundColor로 색상까지 지정할 수 있었습니다.

 

제목과 내용의 간격을 띄운 모습

다음은 NSMutableParagraphStyle을 사용해 제목부분(dev.geeyong)과 내용의 간격을 조절하는 과정입니다.

 

NSMutableParagraphStyle은 회색 @gxxyxxg 텍스트와 아래 내용사이에 간격을 넣기 위해 회색 텍스트를 적용한 부분 뒤에 넣어줍니다.

 

let paragraphStyle = NSMutableParagraphStyle()

paragraphStyle.lineSpacing = 4

let range = NSMakeRange(0, attributedText.string.count)

attributedText.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: range)

 

NSMutableParagraphStyle의 lineSpacing = 간격을 설정해주고 NSMakeRange을 통해 range을 설정해줍니다

그리고 addAttribute을 통해 NSAttributedString.Key.paragraphStyle을 설정해줍니다