2016-06-19 3 views
1

학습 스위프트. 나는 UIButton 클래스를 보유하고 있습니다.방향 변경 후 사용자 지정 UIButton 배경

class CustomBtn: UIButton { 
    var shadowLayer: CAShapeLayer! 
    var shadowAdded: Bool = false 

    required init(coder aDecoder: NSCoder) { 
     super.init(coder: aDecoder)! 

    } 

    override func layoutSubviews() { 
     super.layoutSubviews() 

    } 


    // Only override drawRect: if you perform custom drawing. 
    // An empty implementation adversely affects performance during animation. 
    override func drawRect(rect: CGRect) { 
     super.drawRect(rect) 

     shadowLayer     = CAShapeLayer() 
     shadowLayer.path   = UIBezierPath(roundedRect: bounds, cornerRadius: 5).CGPath 
     shadowLayer.fillColor  = UIColor(netHex: Colors.Red1.value).CGColor 
     shadowLayer.shadowColor  = UIColor.darkGrayColor().CGColor 
     shadowLayer.shadowPath  = shadowLayer.path 
     shadowLayer.shadowOffset = CGSize(width: 2.0, height: 2.0) 
     shadowLayer.shadowOpacity = 0.8 
     shadowLayer.shadowRadius = 2 

     layer.insertSublayer(shadowLayer, atIndex: 0) 
    } 
} 

그리고 이것은 내 출력 : 여기있다

enter image description here

그러나 나는 방향을 변경할 때

enter image description here

당신은 버튼 배경을 얻기 위해 어떻게 할 것인지 (붉은 색과 그림자) 어떤 방향으로 너비를 채우시겠습니까?

+0

크기 클래스와 자동 레이아웃을 사용하지 않는 이유는 무엇입니까? 스택보기를 사용하면보다 신속하게 대응할 수 있습니다. – Jeet

답변

1

drawRect을 실제로 덮어 쓸 필요가 없으므로 위에있는 설명에 충실하는 것이 가장 좋습니다. 그러나 문제는 버튼의 경계를 기반으로 레이어 경로를 설정하는 것이지만 장치를 회전 할 때 경계가 변경되지만 레이어를 업데이트하지 않는 것입니다.

또한 버튼의 레이어 자체에 속성을 설정하여 많은 효과를 얻을 수 있습니다. commonInit에 추가하여 당신은 당신의 클래스를 얻을 수

class CustomBtn: UIButton { 

    required init(coder aDecoder: NSCoder) { 
     super.init(coder: aDecoder)! 
     self.commonInit() 
    } 

    override init(frame:CGRect){ 
     super.init(frame: frame) 
     self.commonInit() 
    } 

    func commonInit(){ 

     self.layer.backgroundColor = UIColor(netHex: Colors.Red1.value).CGColor 
     self.layer.cornerRadius = 5 

     self.layer.shadowColor  = UIColor.darkGrayColor().CGColor 
     self.layer.shadowOffset = CGSize(width: 2.0, height: 2.0) 
     self.layer.shadowOpacity = 0.8 
     self.layer.shadowRadius = 2 
    } 
} 

약간 더 성능이 좋은 것으로 : 나는이 당신의 클래스를 변경 할

self.layer.shadowPath  = UIBezierPath(roundedRect: bounds, cornerRadius: 5).CGPath 

을하지만 당신은 또한 추가 할거야 할 경우 :

override var bounds: CGRect{ 
     didSet{ 
      self.commonInit() 
     } 
    } 

경계가 바뀌면 그림자 경로가 업데이트됩니다.

관련 문제