728x90
[iOS] 커스텀 버튼 컴포넌트 하이라이트 처리
이 화면의 버튼을 구현해야 했다. 이 버튼이 이 화면에 한정해서 나오지 않기 때문에, 버튼 컴포넌트를 만들어서 구현해보았다.
final class LargeSelectButton: UIButton {
private let iconImageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
return imageView
}()
let topTitleLabel: UILabel = {
let label = UILabel()
label.font = UIFont.carmuFont.headline1
label.textColor = UIColor.semantic.textPrimary
return label
}()
let bottomTitleLabel: UILabel = {
let label = UILabel()
label.font = UIFont.carmuFont.subhead3
label.textColor = UIColor.semantic.textPrimary
return label
}()
override var isHighlighted: Bool {
didSet {
if isHighlighted {
// 버튼이 하이라이트 상태일 때 색상
backgroundColor = UIColor.semantic.accPrimary
topTitleLabel.textColor = UIColor.semantic.textSecondary
bottomTitleLabel.textColor = UIColor.semantic.textSecondary
} else {
// 버튼이 하이라이트 상태가 아닐 때 원래 색상으로 변경
backgroundColor = UIColor.semantic.backgroundDefault
topTitleLabel.textColor = UIColor.semantic.textPrimary
bottomTitleLabel.textColor = UIColor.semantic.textPrimary
}
}
}
init(topTitle: String, bottomTitle: String, imageName: String) {
super.init(frame: .zero)
// 서브뷰 내용 설정
topTitleLabel.text = topTitle
bottomTitleLabel.text = bottomTitle
iconImageView.image = UIImage(named: imageName)
// 백그라운드, 그림자 설정
backgroundColor = UIColor.semantic.backgroundDefault
layer.cornerRadius = 20
layer.shadowColor = UIColor.theme.blue6?.cgColor
layer.shadowOffset = CGSize(width: 0, height: 0)
layer.shadowRadius = 8
layer.shadowOpacity = 0.2
// 서브뷰 추가
addSubview(topTitleLabel)
addSubview(iconImageView)
addSubview(bottomTitleLabel)
// Auto Layout 설정
topTitleLabel.snp.makeConstraints { make in
make.top.equalToSuperview().offset(28)
make.centerX.equalToSuperview()
}
iconImageView.snp.makeConstraints { make in
make.top.equalTo(topTitleLabel.snp.bottom).offset(16)
make.centerX.equalToSuperview()
make.width.equalTo(120)
make.height.equalTo(70)
}
bottomTitleLabel.snp.makeConstraints { make in
make.top.equalTo(iconImageView.snp.bottom).offset(25)
make.centerX.equalToSuperview()
}
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
}
init을 통해 위, 아래 텍스트 라벨에 들어갈 내용을 설정하고, 이미지를 Assets에 넣어놓고 그 이미지의 이름을 가지고 불러오는 방식을 구상했다. 여기서 볼 것은, highlight 처리, 그러니까 탭이 될 때만 색이 변하는 것을 override var isHighlighted를 통해 구현할 수 있다는 것을 새롭게 알게 되었다.
한 1시간 동안, 버튼이 클릭될 때만 컴포넌트들의 색이 바뀌는 방법에 대해 알아보는 삽질을 경험했는데, isHighlight라는 변수가 있어서 그거 그냥 오버라이드 해서 쓰면 된다는 사실을 알았다.
728x90
'iOS' 카테고리의 다른 글
[iOS] Firebase만 가지고 리더보드 만들어보기 (0) | 2024.07.29 |
---|---|
[iOS] Naver Search API로 지역 검색 구현하기 (3) | 2024.07.22 |
[iOS] MapKit 주소 자동검색 구현하기 (0) | 2024.01.07 |
[iOS] CoreData Attribute 변경 시 나타나는 Migration 문제 해결(code=134140) (1) | 2024.01.07 |
[Swift] init과 Conveience init 그리고 ? (0) | 2023.10.14 |
댓글