[iOS/Swift] UIButton 익스텐션으로 vertical 정렬

chaentopia·2023년 2월 17일
0

extension UIButton {
  
    
    func alignTextBelow(spacing: CGFloat = 4.0) {
            guard let image = self.imageView?.image else {
                return
            }

            guard let titleLabel = self.titleLabel else {
                return
            }

            guard let titleText = titleLabel.text else {
                return
            }

            let titleSize = titleText.size(withAttributes: [
                NSAttributedString.Key.font: titleLabel.font as Any
            ])

            titleEdgeInsets = UIEdgeInsets(top: spacing, left: -image.size.width, bottom: -image.size.height, right: 0)
            imageEdgeInsets = UIEdgeInsets(top: -(titleSize.height + spacing), left: 0, bottom: 0, right: -titleSize.width)
        }
}

익스텐션 이거 하나면 끝!!

private let editButton : UIButton = {
        let button = UIButton()
        button.setTitle("프로필 편집", for: .normal)
        button.titleLabel?.font = .systemFont(ofSize:10)
        button.setTitleColor(.white, for: .normal)
        button.setImage(UIImage(named: "profile_editImg")! as UIImage, for: .normal)
        button.alignTextBelow(spacing: 8) //이렇게 넣어주기!!
        return button
    }()

이렇게 사용하면 간단하다!! spacing 값에 따라서 텍스트와 이미지 사이 간격이 결정된다.

이런 모양으로 예쁘게 vertical 정렬 가능!

profile
the pale blue dot

0개의 댓글