lgvv98

[UIKit] UILabel Inset 본문

apple/Docs, iOS, Swift

[UIKit] UILabel Inset

lgvv 2023. 6. 23. 16:20

UILabel Inset

 

UILabel의 text와 근간이 되는 label의 고유 view가 가지는 것 사이에 여유공간을 주기 위한 코드

 

InsetLabel

/// UILabel의 text와 컨테이너 사이의 inset값을 설정할 수 있는 커스텀 라벨
final class InsetLabel: UILabel {
    
    /// text와 UILabel 사이의 inset값을 설정
    var edgeInsets: UIEdgeInsets = .init(top: 2.0, left: 8.0, bottom: 2.0, right: 8.0)
    
    override func drawText(in rect: CGRect) {
        super.drawText(in: rect.inset(by: edgeInsets))
    }

    override var intrinsicContentSize: CGSize {
        let size = super.intrinsicContentSize
        
        return CGSize(width: size.width + edgeInsets.left + edgeInsets.right,
                      height: size.height + edgeInsets.top + edgeInsets.bottom)
    }

    override var bounds: CGRect {
        didSet {
            preferredMaxLayoutWidth = bounds.width - (edgeInsets.left + edgeInsets.right)
        }
    }
}

 

 

Usage)

private lazy var customLabel: InsetLabel = {
        $0.font = UIFont.systemFont(ofSize: 11, weight: .regular)
        $0.textColor = UIColor.blue
        $0.edgeInsets = .init(top: 5, left: 10, bottom: 5, right: 10)
        $0.cornerRadius = 6
        $0.backgroundColor = UIColor.blue.withAlphaComponent(0.4)
        return $0
    }(InsetLabel())

 

iOS12부터 개발을 하다보니 UIKit을 주로 사용했었는데,

최근에는 SwiftUI를 더 많이 사용하다보니 UILabel 사이에 공간을 어떻게 주는지 오랜만에 찾아봤어서 감회가 새로웠다.

 

 

언젠가는 UIKit을 아예 모르는 분들이 더욱 많아지지 않을까란 생각이 든다.

'apple > Docs, iOS, Swift' 카테고리의 다른 글

[iOS] CoreData 정리 이론 (1/2)  (0) 2023.12.10
[Swift] plain ol' data(POD)  (0) 2023.08.08
[WWDC23] Meet MapKit for SwiftUI  (0) 2023.06.18
[XCode 15.0 beta] Preview Macro Bug  (0) 2023.06.08
[Swift] 커링(Currying)  (1) 2023.02.28
Comments