김경록의 앱 개발 여정

[Swift UIKit] Button Configuration 사용 시 의도치않은 inset 줄이기 본문

TIL

[Swift UIKit] Button Configuration 사용 시 의도치않은 inset 줄이기

Kim Roks 2025. 2. 7. 20:03

 

일반적인 방식

일반적인 방식으로 버튼 정의 시 기본적으로 콘텐츠 사이즈에 한해 터치영역을 제공

    let testButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("Test", for: .normal)
        button.backgroundColor = .green
        
        return button
    }()

 

 

테스트 예시로 button.BackgroundColor를 변경한 모습

별도의 너비를 주지않을 경우 내부 Text나 Image에 따라서 터치 영역을 딱 맞게 자동으로 제공

 

 

Button Configration 사용 시 모습

 

이미지 + 텍스트를 사용해야할때 buttonConfigation을 자주 사용하는데

UIButton.Configuration을 사용하면 iOS는 버튼의 가독성과 사용성을 높이기 위해 내부적으로 패딩(ContentInsets)을 자동 추가하기 때문

 

하지만 터치 영역 또한 넓어진것이며 레이아웃에도 영향을 주기 때문에 의도치 않은 계산작업이 추가로 들어갈 수 있음

필요에 따라 contentInsets 속성을 수정하여 기존 방식과 같은 너비를 가지도록 설정이 가능

 private func createButtonConfiguration(image: UIImage, title: String) -> UIButton.Configuration {
        var configuration = UIButton.Configuration.plain()
        //글자와 이미지의 패딩
        configuration.imagePadding = 2
        configuration.image = image
       	
        configuration.contentInsets = NSDirectionalEdgeInsets(
            top: 0,
            leading: 0,
            bottom: 0,
            trailing: 0
        )
       
        return configuration
    }
    
    private lazy var commentsLikebutton: UIButton = {
        let button = UIButton(
            configuration:
                createButtonConfiguration(
                    image: .somethingIamge,
                    title: "좋아요"
                )
        )

        button.backgroundColor = .magenta
        
        return button
    }()

 

 

반대로 필요시 넓히는것도 가능

 

적용 시

좌우 인셋이 줄어든 모습