티스토리 뷰

UIButton에 background를 상태에 따라 설정하기 위해서는 따로 extension이 필요합니다.

(왜인지 모르겠는데 기본으로 제공되지 않습니다)

 

extension UIButton {
    func setBackgroundColor(_ color: UIColor, for state: UIControl.State) {
        UIGraphicsBeginImageContext(CGSize(width: 1.0, height: 1.0))
        guard let context = UIGraphicsGetCurrentContext() else { return }
        context.setFillColor(color.cgColor)
        context.fill(CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0))

        let backgroundImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        setBackgroundImage(backgroundImage, for: state)
    }
}

다음과 같이 설정한 후, 이렇게 사용하면 됩니다. (기본 상태)

button.setBackgroundColor(.black, for: .normal)

선택되거나, 비활성화 됬을때의 색을 설정하고 싶다면 다음과 같이 사용합니다.

button.setBackgroundColor(.black, for: .selected)
button.setBackgroundColor(.black, for: .disabled)

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함