2017-06-26 94 views
1

我有UIButtonmainStoryboard。它有白色UIColor和橙色突出显示的颜色。直接从高亮颜色切换颜色到另一种颜色

我想在选择按钮后立即更改此按钮的颜色。

理想的结果

White(default) -> orange(highlighted) -> green(animated) -> white(default) 

然而,对于下面的代码之前,从橙色到绿色的颜色变化就变成白色不久。

当前结果

White(default) -> orange(highlighted) -> White(default) -> green(animated) -> white(default) 

我怎么能直接从突出橙色到绿色切换颜色?

UIView.animate(withDuration:0, animations: {() -> Void in 
     cell.buttons[index].backgroundColor = UIColor.green 

    }) { (Bool) -> Void in 
     UIView.animate(withDuration: 0.5, animations: {() -> Void in 
      cell.buttons[index].backgroundColor = UIColor.green 

     }, completion: { (Bool) -> Void in 
      UIView.animate(withDuration: 0, animations: {() -> Void in 
       cell.buttons[index].backgroundColor = UIColor.white 
      }, completion:nil) 
     }) 
    } 
+0

你的UIButton的类型是什么?确保它在故事板中设置为自定义。 –

+0

你用什么方法为你的按钮获得橙色的“高亮颜色”? – DonMag

回答

1

您的动画代码看起来不错,但动画是两个状态之间的事务,它需要时间(持续时间)。所以尽量不要持续时间为0秒的动画,因为在这种情况下,动画是无用的。

你的问题似乎有按钮侦听器的错误。点击按钮即可将颜色更改为橙​​色,即touchDown。然后,你要尽快释放按钮做颜色变化,这是touchUpInside

所以尝试了这一点,该代码添加到您的viewDidLoad

yourButton.addTarget(self, action:#selector(btnShowPasswordClickHoldDown), for: .touchDown) 

yourButton.addTarget(self, action:#selector(btnShowPasswordClickRelease), for: .touchUpInside) 

,然后用有效的持续时间

添加动画
func btnShowPasswordClickHoldDown(){ 
    UIView.animate(withDuration: 0.5, animations: {() -> Void in 
     self.yourButton.backgroundColor = UIColor.orange 
    }, completion:nil) 
} 

func btnShowPasswordClickRelease(){ 
    UIView.animate(withDuration: 0.5, animations: {() -> Void in 
     self.yourButton.backgroundColor = UIColor.green 

    }, completion: { (Bool) -> Void in 
     UIView.animate(withDuration: 0.5, animations: {() -> Void in 
      self.yourButton.backgroundColor = UIColor.white 
     }, completion:nil) 
    }) 
} 
相关问题