위의 결과 출력을 위해 UILabel 이 몇개 사용됐을까요. 

'한 개' 사용됐습니다. ^^  

(소수점 기준으로 두번째 열이 정렬된 것도 주목해 주세요.)

이번에도 여전히 UILabel 사용량 경량화?!에 대한 글을 작성 중입니다. ㅋ.ㅋ



Title -------------------- value 1

Title -------------------- value 2


위와 같은 패턴의 화면(테이블 구조?!)을 구성할 때 역시나 대체로 각 행마다 UILabel 두 개를 구성합니다. value 부분에 통화(currency) 값이 들어갈 경우에 우측 정렬(NSTextAlignmentRight)을 하곤 합니다.

그리고 레이아웃 위치 지정을 위해 오토레이아웃을 잘 사용해야 하는 경우가 생기는데 이 또한 UILabel 한 개만 사용해서 모두 표현할 수 있습니다.


let attrString = NSMutableAttributedString()
attrString.append(NSAttributedString(string: "product1", attributes: [.font : UIFont.preferredFont(forTextStyle: .headline)]))
attrString.append(NSAttributedString(string: "\t$10.00\n", attributes: [.font : UIFont.preferredFont(forTextStyle: .caption1)]))
attrString.append(NSAttributedString(string: "product2", attributes: [.font : UIFont.preferredFont(forTextStyle: .headline)]))
attrString.append(NSAttributedString(string: "\t$100.0", attributes: [.font : UIFont.preferredFont(forTextStyle: .caption1)]))
        
let paragraph = NSMutableParagraphStyle()
paragraph.tabStops = [NSTextTab(textAlignment: .left, location: 150, options: [.columnTerminators : NSTextTab.columnTerminators(for: Locale.current)])]
attrString.addAttributes([.paragraphStyle : paragraph], range: NSRange(location: 0, length: attrString.length))
        
label.attributedText = attrString


그리고 여기에는 location 150 을 이용하여 탭의 위치를 조정한 것보다 더 눈여겨 봐야할 것이 있습니다. 

바로 options:NSTextTab.OptionKey.columnTerminators Key 의 사용인데요. 

ValuecolumnTerminators(for: Locale.current) 를 이용해서 캐릭터 셋을 넘겼습니다.


그로 인하여 통화(currency)의 소수점(decimal separator)를 기준으로 열이 정렬됩니다. 

이를 통해서 테이블 구조와 유사한 정렬 상태를 유지할 수 있습니다.


이제 아래의 화면처럼 '.' (Decimal Separator) 를 기준으로 탭 텍스트가 정렬된 것을 볼 수 있습니다.

복잡하게 여러개의 UILabel 을 만들 필요 없이 한 개의 Label 에서 '테이블 구조 UILabel' 을 생성하는 방법을 알아봤습니다.






+ Recent posts