2016-06-14 4 views
0

사용자 지정 UIButton의 배경색을 변경하는 방법을 아는 사람이 있습니까? 당신은 이미지에서 볼 수 있듯이단추를 눌렀을 때 사용자 지정 UIButton (CoreGraphics)의 배경색을 변경하십시오.

enter image description here

플롯이라는 버튼이 주황색의 배경 색상을 가지고있다. 그러나 왼쪽 버튼 (검은 색 삼각형)은 주황색이 아닙니다.

내가 원하는 것은 "plot"또는 "award"버튼을 누르면 그 옆의 삼각형 버튼도 함께 변경됩니다.

func drawTriangle() { 
    //Move draw rect code into here 
} 

과의 drawRect에서이 함수를 호출 :

@IBDesignable class LeadingButton: UIButton { 

override func drawRect(rect: CGRect) { 

    // *Draw triangle button: 

    // Create context for triangle 
    let context = UIGraphicsGetCurrentContext() 

    // *Put information into context: 

    // Info for drawing triangle: 
    CGContextMoveToPoint(context, 17, 0) 
    CGContextAddLineToPoint(context, 0, 40) 
    CGContextAddLineToPoint(context, 17, 40) 
    CGContextAddLineToPoint(context, 17, 0) 

    // Info color triangle 
    CGContextSetFillColorWithColor(context, UIColor.blackColor().CGColor) 

    // Color in triangle with specified color 
    CGContextFillPath(context) 

    // Draw triangle 
    CGContextStrokePath(context) 
} 
} 

class MovieDetailController: UIViewController { 

override func viewDidLoad() { 
     super.viewDidLoad() 
    // For changing background color of buttons 
     self.buttonArray = [plotB, directorB, writerB, actorsB, countryB, awardB, posterB, leadingB, trailingB] 

    } 

    func isButton(pressed: Int) { 

     switch pressed { 
     case 0...8: 

      let selectedButton = buttonArray[pressed] 
      selectedButton.backgroundColor = UIColor.orangeColor() 

      var idDictionary = [0:0, 1:1, 2:2, 3:3, 4:4, 5:5, 6:6] 
      idDictionary.removeValueForKey(pressed) 

      for (_, value) in idDictionary { 

       if value == 6 { 

       } 
       else { 

        let remainButtons = buttonArray[value] 
        remainButtons.backgroundColor = UIColor.blackColor() 
       } 
      } 

     default: 
      print("test") 
     } 

    } 

답변

0
지금처럼 그리기 기능에 그리기 코드를 이동

:

여기 내 코드입니다. 또한 당신이 색상의 지시 버튼에 변수를 추가 할 수 있습니다 다음

override func drawRect(rect: CGRect) { 
    super.drawRect(rect) 
    drawTriangle() 
} 

의 drawRect

에서 슈퍼를 호출 할 수 있는지 확인하고, 설정 않았다 당신은 그럼 그냥 가지고 삼각형 색상

var triangleColor:UIColor = UIColor.blackColor() { 
    didSet { 
     drawTriangle() 
    } 
} 
을 설정할 수 있습니다 당신이 삼각형 그리기 색상 :

은 교체 :

CGContextSetFillColorWithColor(context, UIColor.blackColor().CGColor) 

새로운 색상의 설정이없는 경우

(triangleButtonVariable).triangleColor = YourColour 
+0

시도했지만 작동하지 않았습니다. 디버그 콘솔에서도 경고 메시지가 나타납니다. : CGContextDrawPath : 컨텍스트 0x0이 잘못되었습니다. 백 트레이스를보고 싶다면 CG_CONTEXT_SHOW_BACKTRACE 환경 변수를 설정하십시오. 언제든지 drawRect를 호출 할 수 없기 때문입니까? 나는 그것을 어딘가에 읽었다. – Kelvin

0

:로 : 그런 다음

CGContextSetFillColorWithColor(context, triangleColor.CGColor) 

당신은 당신이 버튼을 눌러 플롯/상 있는지 확인하고 사용하여 해당 버튼의 색상을 설정 할 수 있어야한다 drawRect 내부에서 (또는에서) 수행되면 유효하지 않은 컨텍스트 오류가 발생합니다.

새 색상을 설정 한 다음 버튼에 setNeedsDisplay()를 말하십시오.

관련 문제