카테고리 없음

swift 버튼에 이미지와 글 같이 넣는 방법 iOS 15 부터 변경되었으니 알아보자

kingarthur 2024. 7. 11. 18:48

일단 버튼에 이미지를 같이 넣고 싶었는데 이전 방식으로하니 오류가 나서 찾아보게 되었다. 

오류 메세지도 더이상 지원이 안된다고 되어있었다.


이런 버튼들을 만들고 싶을 때 이전에는 UIImageInset으로 이미지를 설정해주었었다.

button.setImage(UIImage(named: "message"), for: .normal)
button.imageEdgeInsets = UIEdgeInsets(top: 5, left: 0, bottom: 5, right: 12)

그러나 이는 iOS 15.0에서 더이상 지원하지 않는다고 하여 다른 방법을 찾아보다가, UIButton에 대해 많은 부분이 업데이트된 것을 알게 되었다.

'imageEdgeInsets' was deprecated in iOS 15.0: This property is ignored when using UIButtonConfiguration

🐻 Configuration

iOS 15 에서는 버튼의 padding과 insets을 control할 수 있는 세 가지 옵션을 새로 소개하고 있다.

  • .titlePadding : Padding between the title and subtitle labels.
  • .imagePadding : Padding between the button’s image and text.
  • .contentInsets: Padding from the button’s content area to its bounds.

이를 사용하기 위해 configuration을 정의해야한다.

//configuration으로 버튼 속성을 먼저 정의
var configuration = UIButton.Configuration.tinted()
configuration.image = UIImage(systemName: "heart")
configuration.imagePlacement = .trailing
configuration.imagePadding = 30 
configuration.subtitle = "서브타이틀"
configuration.title = "타이틀"
configuration.title

//버튼 생성 후 정의한 configuration 넣어주기
let button = UIButton(configuration: configuration, primaryAction: nil)
  • 간격 설정 : NSDirectionalEdgeInsets를 적용하여 세부적으로 버튼과 content간 간격을 조절할 수 있다.
configuration.contentInsets = NSDirectionalEdgeInsets(top: 17, leading: 30, bottom: 18, trailing: 105)
  • 이미지 색깔 변경
configuration.baseForegroundColor = UIColor(named:.._)

🐻 ConfigurationUpdateHandler

버튼을 눌렀을 때 action 추가 (이미지 변경)

button.configurationUpdateHandler = { button in
      var config = button.configuration
      config?.image = button.isHighlighted ? UIImage(systemName: "heart.fill") : UIImage(systemName: "heart")
      button.configuration = config
}

참고: https://zeddios.tistory.com/1291, https://velog.io/@wannabe_eung/iOS-UIButton-Configuration-%EC%82%AC%EC%9A%A9%ED%95%B4%EB%B3%B4%EA%B8%B0-in-iOS-15