[TIL] UIButton configuration

박주하·2025년 6월 26일

UIButton.Configuration


// 기존 방식
// 스타일을 직접 설정해야 하고, 코드가 분산되어 있음
let button = UIButton()
button.setTitle("확인", for: .normal)
button.setTitleColor(.white, for: .normal)
button.backgroundColor = .systemBlue
button.layer.cornerRadius = 8

// 새로운 방식
// 스타일이 한 곳에 모여 있어 깔끔함
var config = UIButton.Configuration.filled()
config.title = "확인"
config.image = UIImage(systemName: "checkmark")
config.baseBackgroundColor = .systemBlue
config.baseForegroundColor = .white
config.imagePadding = 8

let button = UIButton(configuration: config)
  • Swift에서 UIButton을 꾸미는 새로운 방식으로, iOS 15 이상부터 사용 가능
  • 버튼의 타이틀, 이미지, 색상, 폰트, 간격, 여백 등 스타일 요소를 한 번에 설정할 수 있는 구조체
  • 모든 스타일을 구조화해서 관리 가능
  • 기존보다 더 읽기 쉽고, 유지보수가 쉬움

1. 버튼 스타일 종류

  • .plain(): 투명 배경, 기본 버튼
  • .filled(): 색이 채워진 버튼 (기본 배경 색)
  • .tinted(): 배경은 연한 색, 테두리는 강조
  • .gray(): 회색 버튼 (취소 등 보조용)

2. 주요 속성들

var config = UIButton.Configuration.filled()

config.title = "버튼"					 	// 제목
config.subtitle = "클릭!"                    // 부제목
config.image = UIImage(systemName: "bolt.fill")
config.imagePadding = 8                     // 이미지-텍스트 간격
config.cornerStyle = .capsule               // 모서리 둥글게
config.baseBackgroundColor = .systemGreen   // 배경색
config.baseForegroundColor = .white         // 텍스트 & 이미지 색

3. 버튼 상태별 설정

button.configurationUpdateHandler = { button in
    switch button.state {
    case .highlighted:
        button.configuration?.baseBackgroundColor = .darkGray
    case .disabled:
        button.configuration?.title = "사용 불가"
    default:
        button.configuration?.baseBackgroundColor = .systemBlue
    }
}
  • configurationUpdateHandler를 활용해 상태에 따라 다르게 설정 가능!

4. 버튼 액션

button.addTarget(self, action: #selector(handleTap), for: .touchUpInside)

// iOS 14+ 부터 사용 가능
button.addAction(UIAction { _ in
    print("클릭!")
}, for: .touchUpInside)
  • .addTarget 또는 .addAction 활용

5. 사용 예

let button = UIButton(type: .system)
var config = UIButton.Configuration.filled()
config.title = "로그인"
config.image = UIImage(systemName: "lock.fill")
config.imagePadding = 8
config.cornerStyle = .medium
config.baseBackgroundColor = .systemIndigo

button.configuration = config
button.addTarget(self, action: #selector(didTapLogin), for: .touchUpInside)

📌 정리

항목설명
title, subtitle버튼 텍스트, 부제목
image시스템 이미지 사용
baseBackgroundColor배경 색
baseForegroundColor글자 및 이미지 색
imagePlacement, imagePadding이미지 위치 & 간격
cornerStyle모서리 스타일 (.medium, .capsule 등)
contentInsets여백 설정
configurationUpdateHandler상태별 동적 스타일 지정 가능

0개의 댓글