2016-08-13 4 views
1

원형의 녹색 버튼이 생성되었습니다.스위프트 3.0 : 한 번 누르면 버튼 색상 변경

다음
import UIKit 

class CircularButton: UIButton { 

@IBInspectable var fillColor: UIColor = UIColor.green 

override func draw(_ rect: CGRect) { 

    let path = UIBezierPath(ovalIn: rect) 
    fillColor.setFill() 
    path.fill() 

    } 
} 

스크린 샷 : 여기 색상을 정의하고 다음과 같이 형성 한 CircularButton.swift입니다. 버튼을

enter image description here

내가 빨간색으로 색상을 변경하려면 눌렀습니다. 아래 함수를 정의했습니다.

@IBAction func circularButtonPressed(_ sender: CircularButton) { 
    sender.fillColor = UIColor.red 
    sender.draw(CGRect(x: 0, y: 0, width: sender.frame.width, 
         height: sender.frame.height)) 
} 

색상이 빨간색으로 변경되지 않는 이유는 무엇입니까?

: I 줄 아래에 추가하는 경우 : 빨간색으로

sender.backgroundColor = UIColor.white 

을 위의 함수에서, 버튼 색상 변경.

는 당신의 도움을 주셔서 감사합니다.

+1

읽기 [뷰 도면주기 (https://developer.apple.com/

라인이 draw(_:)를 호출 제거 라이브러리/ios/documentation/WindowsViews/개념/ViewPG_iPhoneOS/WindowsandViews/WindowsandViews.html # // apple_ref/doc/uid/TP40009503-CH2-SW10). –

+0

올바른 방향으로 보내 주셔서 감사합니다. – gbdcool

답변

1

draw(_:)을 코드 내부에서 직접 호출하면 안됩니다. 컨트롤을 다시 그려야한다고 iOS에 알릴 필요가 있습니다.

@IBAction func circularButtonPressed(_ sender: CircularButton) { 
    sender.fillColor = UIColor.red 
} 

그리고 fillColor 속성에 옵저버를 추가합니다 : 약

@IBInspectable var fillColor: UIColor = UIColor.green { 
    didSet(oldColor) { 
     if fillColor != oldColor { 
      self.setNeedsDisplay() 
     } 
    } 
} 
+0

정말 고마워요. 이것이 제가 찾고 있던 것입니다. – gbdcool