【问题标题】:Change button background color dynamically like progress bar像进度条一样动态更改按钮背景颜色
【发布时间】:2015-08-24 08:32:50
【问题描述】:

我正在尝试在 Swift 中实现具有可变背景颜色的按钮。但我不想改变整个按钮的颜色。我希望它像进度条一样改变。例如,会有一个特定的时间值,按钮的背景颜色应该随着动画从右到左变化。 我见过这样的应用程序。任何人都可以提供如何做到这一点的线索吗?

【问题讨论】:

    标签: swift button uibutton


    【解决方案1】:

    不要被按钮只是UIButton 的想法所束缚。按钮可以是带有手势识别器的视图,也可以是顶部带有透明按钮的视图。它可能是一个带有您不断更新的背景图像的按钮。如何构建您所描述的内容有很多选择。这完全取决于您想要如何完成它的效果。在进度完成之前,显示进度的按钮通常会被禁用,因此您可以轻松地使用进度指示视图,当进度完成时,该视图会被“真实”按钮取代。

    【讨论】:

    • 你能举例说明一下吗?
    【解决方案2】:

    也许这对你有帮助。

     func changeButtonColors(){
        //let myBtn
    
        let timer = NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: "changeColor", userInfo: nil, repeats: true)
    
        timer.fire()
    
     }
    
     //cloros to iterate over each time
     let colorChoice = [UIColor.blackColor(), UIColor.blueColor(), UIColor.redColor()]  
      var counter = 0   //tracking variable
    
     //this gets called when by the timer
     //currently it is supposed to go on forever. 
     func changeColor(){
            //suppose i have the button outlet named myBtn
    
            UIView.animateWithDuration(2.0, animations: { () -> Void in
                myBtn.backgroundColor = colorChoice[counter]
    
                if counter < colorChoice.count{
                    counter++
                }else{
                    counter = 0
                    //or disable the alert
                    //timer.invalidate()
                }
            })
        }
    

    这里的 myBtn 是 View Controller 的一个出口。在我们的例子中,我们使用 Timer 在特定时间每 2 秒触发一次函数调用。这可以由其他应用程序逻辑派生。

    然后,被调用的函数遍历 UIColor 数组并将其应用于按钮或视图的背景。工作流程是这样的。根据需要更改内容。

    【讨论】:

    • 它将改变整个背景颜色。我要求改变颜色,从右边开始,像进度条一样继续向左。
    猜你喜欢
    • 2014-12-26
    • 2015-06-04
    • 1970-01-01
    • 1970-01-01
    • 2020-01-20
    • 1970-01-01
    • 1970-01-01
    • 2012-08-03
    相关资源
    最近更新 更多