2016-03-27 72 views
2

在我的自定義表格視圖單元格中,我有4個帶有動畫的按鈕(如下所示)。問題是當我使用UIButton時,動畫並不像我想要的那樣動畫。但是當我使用UIView時,它的工作原理與我想要的完全相同。UIView和UIButton之間的動畫差異

該代碼與僅使用不同類型的UIView的區別完全相同。

這部動畫是使用UIButton

Animation with a button

這部動畫是使用UIView

Animation with a UIView

爲了讓事情更清晰,唯一我在代碼中替換的是:

// Test with Buttons 
let button1 = Button() // Subclass of UIButton 
let button2 = Button()  

// Test with UIViews 
let button1 = UIView() 
let button2 = UIView() 

問:
有人能告訴我爲什麼UIButton行爲有所相比正常UIView


起初我以爲通過不張貼代碼,我可以使這個問題更容易,因爲這兩種測試都使用完全相同的代碼(除「元素」讀(元素爲UIViewUIButton),和思想也許問題就出在「分子」之間的區別我現在意識到,這是我的錯

我的代碼:。

class CustomView: UIView { 

    private var base: [NSLayoutConstraint] = [] 
    private var open: [NSLayoutConstraint] = [] 

    var buttons: [UIView] = [] 

    private var active = false 

    override init(frame: CGRect) { 
     super.init(frame: frame) 

     let button1 = CustomButton(frame: CGRectZero, color: UIColor.yellowColor().CGColor) 
     let button2 = CustomButton(frame: CGRectZero, color: UIColor.redColor().CGColor) 

    // let button1 = UIView(); button1.backgroundColor = UIColor.yellowColor() 
    // let button2 = UIView(); button2.backgroundColor = UIColor.redColor() 

     let views = ["button1": button1, "button2": button2] 

     buttons = [button1, button2] 

     buttons.enumerate().forEach { 
      $0.element.translatesAutoresizingMaskIntoConstraints = false 
      addSubview($0.element) 

      addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[button\($0.index + 1)]|", options: [], metrics: nil, views: views)) 

      base += [NSLayoutConstraint(item: $0.element, attribute: .Width , relatedBy: .Equal, toItem: buttons.first!, attribute: .Width , multiplier: 1, constant: 0)] 
     } 

     open += [NSLayoutConstraint(item: buttons.last!, attribute: .Width, relatedBy: .Equal, toItem: buttons.first!, attribute: .Width, multiplier: 0.33, constant: 0)]   
     addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[button1]-0.5-[button2]|", options: [], metrics: nil, views: views)) 
     addConstraints(base) 

     backgroundColor = .blackColor() 
     clipsToBounds = true 
    } 

    required init?(coder aDecoder: NSCoder) { 
     fatalError("init(coder:) has not been implemented") 
    } 

    func changeState() { 
     removeConstraints(active ? open : base); addConstraints(active ? base : open) 

     active = !active 

     UIView.animateWithDuration(0.5, animations: { self.layoutIfNeeded() }) 
    } 
} 

解決方案:
發佈代碼並意外更改按鈕的背景顏色後,我注意到它的行爲是相應的。這讓我意識到我在導致第一個動畫中看到的行爲的按鈕中使用了CAShapeLayer。現在我知道該怎麼解決。如果這篇文章應該關閉或刪除,請告訴我。然後我會刪除答案。並感謝那些試圖幫助的人!

+0

你介意告訴我爲什麼投票嗎?我不介意添加動畫代碼,但是看到它適用於「UIView」,我認爲它會讓帖子不必要地變長。 –

+0

請問您可以添加動畫代碼嗎?這可能是最重要的事情。 – Sulthan

回答

0

沒有你提供更多的細節,我唯一能做的就是猜測你正在目睹的行爲歸結爲按鈕比視圖更不「彈性」,因爲它們具有由其內容決定的「自然」大小(標題和/或圖像)和自動佈局確實喜歡強制執行自然尺寸(正如您從IB的警告中看到的那樣)。

如果您需要更多幫助,請提供更多詳細信息。你真的使用自動佈局?什麼約束?你在做什麼動畫?等等。