apple/iOS, UIKit, Documentation
UILabel Inset and CornerRadius (UIKit)
lgvv
2023. 6. 23. 16:20
UILabel Inset and CornerRadius (UIKit)
UILabel에서 텍스트 주변으로 인셋을 주기 위한 코드
히스토리
- 2023-06-23: InsetLabel 구현
- 2025-01-21: CapusuleLabel 추가
목차
- InsetLabel 전체 코드
- InsetLabel 사용법
- CapsuleLabel 전체 코드
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)
}
}
}
InsetLabel 사용법
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())
CapsuleLabel 전체 코드
개발하다 보면은 칩을 Capsule 처럼 만들어야 하는데 인셋을 주는게 더 나을 때가 많음.
/// UILabel의 text와 컨테이너 사이의 inset값을 설정할 수 있는 커스텀 라벨
final class CapsuleLabel: 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)
}
}
/// `cornerRadius`를 높이의 절반으로 설정
override func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = bounds.height / 2
layer.masksToBounds = true // 클립 영역을 제한
}
}
iOS12부터 개발을 하다 보니까 UIKit을 주로 사용했음.
최근에는 SwiftUI를 더 많이 사용하다보니 UILabel 사이에 공간을 어떻게 주는지 오랜만에 찾아봤어서 감회가 새로웠다.
언젠가는 UIKit을 아예 모르는 분들이 더욱 많아지지 않을까란 생각이 든다.