[swift/UIKit] UIButton에 이미지와 텍스트 vertical로 배치 하기

Hoseon Chu·2022년 11월 25일
0

swift

목록 보기
2/5

UIButton에 세로로 버튼을 배치 하는것은 아주 간단한 기능은 아니였기에
아래와 같이 ext를 이용하여 처리 하였다.

내가 처리 해야 할 버튼UI

View안에 버튼을 넣어서 구현하는 방식

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)
        }
}

사용

class CustomButton: UIView {
	ovveride func viewDidLoad() {
    	super.viewDidLoad()
        boxview.layer.cornoerRadius = 12
        btn.alignTextBelow(spacing: 4)
    }
}
profile
개발자입니다

0개의 댓글