iOS 응용 (swift)
[iOS - swift] 커스텀 버튼(custom button) 만들기
jake-kim
2020. 11. 20. 22:46
목표
- baseButton을 하나 만들고, 공통적으로 baseButton의 속성을 가지면서 각자의 특색있는 커스텀 버튼 생성
BaseButton 생성
- cornerRadius가 4인 Base버튼 클래스 생성
//
// MyBaseButton.swift
// Test
//
// Created by 김종권 on 2020/11/20.
//
import Foundation
import UIKit
class MyBaseButton: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
func setupView() {
layer.cornerRadius = 4
clipsToBounds = true
}
}
- @IBDesignable을 사용할 것이면, BaseButton에 아래 함수 추가
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
setupView()
}
BaseButton의 속성을 갖고 있는 Button추가
- 중요한 것은 BaseButton을 상속받는다면 init을 따로 써주지 않아도 되고, setupView()역시 BaseButton의 속성을 그대로 이용하려면, setupView를 override해서 super.setupView()를 호출하면 해결
//
// MyYellowButton.swift
// Test
//
// Created by 김종권 on 2020/11/20.
//
import Foundation
import UIKit
final class MyYellowButton: MyBaseButton {
override var isHighlighted: Bool {
didSet {
backgroundColor = isHighlighted ? .orange : .gray
}
}
override func setupView() {
super.setupView()
setTitleColor(.yellow, for: .normal)
setTitleColor(.gray, for: .disabled)
}
}
* 이처럼 커스텀 버튼에 공통적인 속성을 적용하고 싶을 땐 BaseButton하나를 만들고, 그것을 상속받으며 setupView를 override하는 형태