iOS (기능)
[Swift] UIButton Highlight 및 Selected Background Color 변경
겸손할 겸
2020. 9. 24. 15:43
[UIButton Background Color]
UIButton의 기본 이미지를 상태값에 따라 변경하는게 가장 깔끔하지만, 만약 이미지를 넘겨받지 않고 색상으로 직접 만들라는 오더가 내려왔을 때, 버튼의 배경색상을 코드로 변경하고, 실행하게 되면 내가 원한 색상이 아니라, 좀 더 탁한 색이 나오게 된다 .
예를 들어, Stack OverFlow에서 사용하는 배경색상 변경 함수를 보면
func setBackgroundColor(color: UIColor) {
self.btn.clipsToBounds = true // add this to maintain corner radius
UIGraphicsBeginImageContext(CGSize(width: 1, height: 1))
if let context = UIGraphicsGetCurrentContext() {
context.setFillColor(color.cgColor)
context.fill(CGRect(x: 0, y: 0, width: 1, height: 1))
let colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.btn.setBackgroundImage(colorImage, for: .highlighted)
}
}
위와 같은 함수로 변경할 수 있다. 사용자가 버튼을 클릭하는 그 순간의 상태값인 highlighted의 컬러를 넘겨받은 컬러로 변경하는 것인데, 여기서 나느 UIColor.yellow로 했을 경우 아래와 같다.
클릭이란 버튼의 노란색이 옅어졌다.
내가원한건 선명한 노란색이었기에, 아래와 같이 원한다.
이 때 사용할 코드가 UIButton을 상속받는 클래스를 하나 생성하여, isHighlighted라는 변수를 오버라이드 하여 사용하면 된다.
class ButtonWithHighlight: UIButton {
override var isHighlighted: Bool {
get {
return super.isHighlighted
}
set {
backgroundColor = UIColor.yellow
super.isHighlighted = newValue
}
}
}
그리고 UIButton을 연결한 스토리보드 및 클래스 Outlet에서 UIButton대신 ButtonWithHighlight로 상속받게 하면 된다.