【问题标题】:switch color directly from highlighted color to another color将颜色直接从突出显示的颜色切换到另一种颜色
【发布时间】:2017-06-26 12:47:44
【问题描述】:

我在mainStoryboard 上有一个UIButton。它具有白色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)
        })
    }

【问题讨论】:

  • 你的 UIButton 是什么类型的?确保它在情节提要中设置为自定义。
  • 您使用什么方法为您的按钮获得橙色的“突出显示颜色”?

标签: ios swift


【解决方案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)
    })
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-17
    • 1970-01-01
    • 1970-01-01
    • 2013-03-26
    • 2013-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多