๊ธฐํƒ€/iOS๐ŸŽ

[iOS/Swift] UILabel์— Padding ๊ฐ’ ์ฃผ๊ธฐ, Label ๋™์ ์œผ๋กœ text ํฌ๊ธฐ์— ๋งž๊ฒŒ ๋Š˜์–ด๋‚˜๊ฒŒ ํ•˜๊ธฐ - ์ฝ”๋“œ๋ฒ ์ด์Šค, Snapkit, then

yujindonut 2022. 7. 6. 22:29
728x90

๋‚˜์˜ ๋ฏธ์…˜ 

1. ๋™๊ทธ๋ž—๊ฒŒ ๋งŒ๋“ค์–ด์•ผํ•จ

2. padding ๊ฐ’์œผ๋กœ ๊ธ€์”จ leading, trailing์— 4์˜ ์—ฌ๋ฐฑ์„ ์ค˜์•ผํ•จ

3. top, bottom ๋„ 2 ์ •๋„์˜ ์—ฌ๋ฐฑ

 

์•ˆ์˜ ๊ธ€์”จ๊ฐ€ ๋Š˜์–ด๋‚ ๋•Œ๋งˆ๋‹ค, ๊ธ€์”จ๊ฐ€ ๋Š˜์–ด๋‚  ์ˆ˜ ์žˆ๋„๋ก!

 

Label์— Padding ๊ฐ’์„ ์ค„ ์ˆ˜๋Š” ์—†๋‹ค!!

์ปค์Šคํ…€ ํ•ด์„œ ๋งŒ๋“ค์–ด์•ผํ•ด์šฉ!

 

 

BasePaddingLabel.swift ํŒŒ์ผ์„ ์ƒ์„ฑํ•ด์ค€๋‹ค.

import UIKit

class BasePaddingLabel: UILabel {
    
    private var padding = UIEdgeInsets(top: 2.0, left: 4.0, bottom: 2.0, right: 4.0)
    
    convenience init(padding: UIEdgeInsets) {
        self.init()
        self.padding = padding
    }
    
    override func drawText(in rect: CGRect) {
        super.drawText(in: rect.inset(by: padding))
    }
    
    //์•ˆ์˜ ๋‚ด์žฌ๋˜์–ด์žˆ๋Š” ์ฝ˜ํ…ํŠธ์˜ ์‚ฌ์ด์ฆˆ์— ๋”ฐ๋ผ height์™€ width์— padding๊ฐ’์„ ๋”ํ•ด์คŒ
    override var intrinsicContentSize: CGSize {
        var contentSize = super.intrinsicContentSize
        contentSize.height += padding.top + padding.bottom
        contentSize.width += padding.left + padding.right
        
        return contentSize
    }
}

 

BasePaddingLabel์„ ์ƒ์†๋ฐ›์€ Label์„ ์ƒ์„ฑํ•ด์ค€๋‹ค.

 

    private let ifSuccessLabel = BasePaddingLabel(padding: UIEdgeInsets(top: 2, left: 4, bottom: 2, right: 4)).then {
        $0.backgroundColor = .lightGray
        $0.font = .systemFont(ofSize: 10, weight: .semibold)
        $0.textColor = .white
        $0.clipsToBounds = true // ์š”์†Œ๊ฐ€ ์‚์ ธ๋‚˜๊ฐ€์ง€ ์•Š๋„๋ก ํ•˜๋Š” ์†์„ฑ
        $0.layer.cornerRadius = 8 // ๋‘ฅ๊ธ€๊ฒŒ ๋งŒ๋“œ๋Š” ์ •๋„
        $0.textAlignment = .center
    }

 

  1. LabelContainerView์•ˆ์— Label์„ ์ง‘์–ด๋„ฃ๊ธฐ
// MARK: Properties
    
private let ifSuccessLabelContainerView = UIView().then {
    $0.makeRounded(cornerRadius: 8.adjusted)
    $0.backgroundColor = .grey_5
    $0.clipsToBounds = true
}
    
private let ifSuccessLabel = UILabel().then {
    $0.setLabel(text: "gggg", color: .white, size: 10, weight: .semiBold)
    $0.textAlignment = .center
}

๋งŒ๋“ค์–ด๋†“์€ UIView์— UILabel์„ ์ง‘์–ด๋„ฃ์–ด์ค๋‹ˆ๋‹ค ~ ..

/// UIView ์•ˆ์— UILabel ๋„ฃ๊ธฐ
ifSuccessLabelContainerView.addSubview(ifSuccessLabel)

/// ๊ฐ„๊ฒฉ ์กฐ์ •
ifSuccessLabelContainerView.snp.makeConstraints {
            $0.centerY.equalTo(privateImageView)
            $0.leading.equalTo(goalTitleLabel.snp.trailing).offset(6)
}
ifSuccessLabel.snp.makeConstraints {
            $0.centerX.equalTo(ifSuccessLabelContainerView)
            $0.centerY.equalTo(ifSuccessLabelContainerView)
            $0.leading.trailing.equalTo(ifSuccessLabelContainerView).inset(4)
            $0.top.bottom.equalTo(ifSuccessLabelContainerView).inset(2)
}

๋‘˜๋‹ค ๋ผ๋ฒจ์— ๋”ฐ๋ผ์„œ ๊ฒ‰์˜ ํ…Œ๋‘๋ฆฌ๊ฐ€ ๋Š˜์–ด๋‚˜๊ฒŒ ๋ฉ๋‹ˆ๋‹ค ~

728x90