-
Text Attributed스유를 써봐유! 2021. 9. 13. 01:00728x90반응형
안녕하세요. iOS 개발자 에이든입니다!👦🏻
이번 시간에는 Text를 부분적으로 이쁘게 꾸미는(?) 방법에 대해 알아볼까 합니다.
이전에 Swift에서는 NSAttributedString을 상속하는
NSMutableAttributedString Class의 Instance를 생성 후 해당 Instance에 여러 조건들을 넣어준 뒤
이를 UILabel의 attributedText에 대입하는 방식으로 Text를 부분적으로 수정했습니다.
하지만 SwiftUI가 나오고 얼마의 시간이 흐른 뒤 이런 방식도 많이 바뀌었는데요!
어떻게 바뀌었는지 함께 봅시다!
기존의 NSMutableAttributedString을 활용한 방식
기존에 늘 사용하던 방식이에요! ViewController와 UILabel에 적용하는 방식으로 NSMutableAttributedString의 Instance를 생성하여 조건들을 넣고 UILabel의 attributedText에 할당하는 방식입니다!
import UIKit class ViewController: UIViewController { @IBOutlet weak var label: UILabel! override func viewDidLoad() { super.viewDidLoad() label.textAlignment = .center label.text = "사이즈 폰트 색깔 테두리 밑줄 배경 가운데줄" //내가 적용하고싶은 폰트 사이즈 let fontSize = UIFont.boldSystemFont(ofSize: 30) let font = UIFont(name:"AppleSDGothicNeo-Light" , size: 30) // label의 text를 가지는 NSMutableAttributedString의 Instance를 생성힙니다. let attributedString = NSMutableAttributedString(string: label.text ?? "") // 아래와 같이 attributedStr에 addAttribute Method를 사용해서 다양한 Custom을 할 수 있어요! // FontSize attributedString.addAttribute(.font, value: fontSize, range: ((label.text ?? "") as NSString).range(of: "사이즈")) // Font attributedString.addAttribute(.font, value: font ?? UIFont(), range: ((label.text ?? "") as NSString).range(of: "폰트")) // Font Color attributedString.addAttribute(.foregroundColor, value: UIColor.blue, range: ((label.text ?? "") as NSString).range(of: "색깔")) // 글자 테두리 (테두리 색과 크기는 글자의 색과 크기를 바꾸는 방법과 동일합니다!) attributedString.addAttribute(.strokeWidth, value:2.0, range: ((label.text ?? "") as NSString).range(of:"테두리")) attributedString.addAttribute(.font, value: fontSize, range: ((label.text ?? "") as NSString).range(of: "테두리")) // 밑줄 attributedString.addAttribute(.underlineStyle, value: NSUnderlineStyle.thick.rawValue, range: ((label.text ?? "") as NSString).range(of:"밑줄")) attributedString.addAttribute(.underlineColor, value: UIColor.red, range: ((label.text ?? "") as NSString).range(of:"밑줄")) // Background Color attributedString.addAttribute(.backgroundColor, value: UIColor.green, range: ((label.text ?? "") as NSString).range(of:"배경")) // 가운데 줄 (value의 숫자가 커질수록 글자가 위로 올라갑니다.) attributedString.addAttribute(.baselineOffset, value: 10, range: ((label.text ?? "") as NSString).range(of:"가운데줄")) // 가운데 줄의 두께! attributedString.addAttribute(.strikethroughStyle, value: 3, range: ((label.text ?? "") as NSString).range(of:"가운데줄")) // UILabel의 attributedText에 Custom한 attributedString을 할당해줍니다. label.attributedText = attributedString } }
자 이제부터는 iOS15, Swift5.5부터 가능한 방식들입니다!
이번에 많이 편리해졌네요ㅠ 사랑해요 애플ㅠㅠㅠ
SwiftUI의 AttributedString
SwiftUI는 이전에는 AttributedString이 따로 없어 Text를 여러 개로 만드는 수밖에 없었어요. 하지만 이번에 AttributedString이 생겨서 훨씬 간단하게 구현할 수 있게 되었습니다. 방법은 위에서 보았던 NSMutableAttributedString과 비슷해요! AttributedString 속성의 Property를 생성해서 조건들을 넣고 이를 Text의 Value로 넣어주면 됩니다!
- underlineStyle이나 strikethroughStyle에 pattern은 기본적으로 아래와 같아요
1. solid (⎼⎼⎼)
2. dash (- - -)
3. dot (∙∙∙)
4. dashDot (-∙-∙)
5. dashDotDot (-∙∙-∙∙)import SwiftUI struct ContentView: View { var body: some View { if #available(iOS 15, *) { Text(attributedString) .padding() } else { // Fallback on earlier versions } } } extension ContentView { @available(iOS 15, *) var attributedString: AttributedString { var text: AttributedString = "사이즈 폰트 색깔 테두리 밑줄 배경 가운데줄 링크" let fontRange = text.range(of: "사이즈 폰트")! let colorRange = text.range(of: "색깔")! let strokeRange = text.range(of: "테두리")! let underlineRange = text.range(of: "밑줄")! let backgroundRange = text.range(of: "배경")! let middlelineRange = text.range(of: "가운데줄")! let linkRange = text.range(of: "링크")! // Font text[fontRange].font = UIFont(name:"AppleSDGothicNeo-Light" , size: 30) // Font Color text[colorRange].foregroundColor = .blue // 글자 테두리 text[strokeRange].strokeColor = .red text[strokeRange].strokeWidth = 1 // 밑줄 text[underlineRange].underlineStyle = .init(pattern: .solid, color: .pink) text[backgroundRange].backgroundColor = .green // 가운데 줄 (baselineOffset의 숫자가 커질수록 글자가 위로 올라갑니다.) text[middlelineRange].baselineOffset = 10 text[middlelineRange].strikethroughStyle = .init(pattern: .dash, color: .pink) // 링크 text[linkRange].link = URL(string: "https://aiden-ios.tistory.com") return text } }
[ Link 예시 ]
희한하게 stroke는 변하지 않네요ㅠ 이유 아시는 분은 댓글 부탁드립니다!
MarkDown을 활용한 방식
AttributedString 외에 MarkDown 문법을 활용한 특정 Custom도 가능합니다!
import SwiftUI struct ContentView: View { var body: some View { VStack(alignment: .center, spacing: 20) { Text("일반 텍스트") Text("*Italics*") Text("**Bold**") Text("***Bold And Italics***") Text("~Strikethrough~") Text("`class Aiden` class Aiden") Text("[Aiden-iOS](https://aiden-ios.tistory.com)") } } }
자 오늘은 이렇게 Text를 부분 Custom하는 방법에 대해 알아보았습니다.
예전에 ViewController에서 작업할때 상당히 귀찮았었는데, 많은 부분이 간소화돼서 좋네요ㅎㅎ
오늘은 여기까지 입니다!
혹시라도 부족하거나 잘못된 부분 그리고 질문 있으시면 언제든 댓글 부탁드려요! 감사합니다!👦🏻👋🏻
728x90반응형'스유를 써봐유!' 카테고리의 다른 글
@AppStorage와 UserDefaults (0) 2021.10.17 NavigationView, NavigationLink (0) 2021.09.26 @State, @Binding, @ObservedObject, @EnvironmentObject (0) 2021.09.05 Custom TabBar (0) 2021.08.15 Prologue (1) 2021.08.01