ios - 在 iOS Swift 中设置按钮事件颜色的简单方法

标签 ios swift

我一直在寻找在单击按钮时更改事件状态的方法。单击按程序重新定位我的 ScrollView 时,我有 4 个按钮。

我正在尝试将背景颜色设置为在单击时淡化一点。我可以设置背景颜色,但单击另一个时它会保持相同的褪色颜色。它不会返回到非事件状态。

有什么简单的方法可以在全局范围内实现这种 onckick 按钮行为?

这是我的按钮点击功能:

@IBAction func tab1(sender: UIButton)

{

    slScrollView.setContentOffset(CGPointMake(0.0, 0.0), animated: true)

    tab1.backgroundColor = UIColor.grayColor()

    tab2.selected = false
    tab3.selected = false
}


@IBAction func tab2(sender: UIButton)
{
    slScrollView.setContentOffset(CGPointMake(0.0, 650.0), animated: true)

    tab2.backgroundColor = UIColor.grayColor()

    tab1.selected = false
    tab3.selected = false

}


@IBAction func tab3(sender: UIButton) {
    slScrollView.setContentOffset(CGPointMake(0.0, 1370.0), animated: true)

    tab3.backgroundColor = UIColor.grayColor()

    tab1.selected = false
    tab2.selected = false
    }

最佳答案

首先,为按钮创建一个 IBOutletCollection(或四个单独的导出)。然后创建一个IBAction 方法并设置所有四个 按钮在点击时触发它。在该方法中,在触发操作的按钮上执行背景淡入淡出动画(作为其 sender 参数传递到处理程序中,然后重置其他导出按钮的状态。

我的编码方式:

// Outlet to all of the buttons. ctrl+drag each button to this outlet.
@IBOutletCollection buttons = [UIButton]()

// Set *all* of the buttons to fire this method.
@IBAction func buttonTapped(sender: AnyObject!) {
    (sender as? UIButton).backgroundColor = <whatever>

    for button in buttons.filter({ $0 != sender }) {
        button.backgroundColor = <default>
    }
}

关于ios - 在 iOS Swift 中设置按钮事件颜色的简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32172581/

相关文章:

swift - 在 Swift 中将 map 从 Firestore 转换为字典

iphone - 实现对 map View Controller 的搜索

PHPSESSID 在每次请求时都会更改而不是持久化

iphone - 将 TableView 转换为具有部分

ios - 解释iOS中Energy Usage Instrument的统计

ios - TableView 复制图像?

ios - 向场景添加大量自定义节点需要很长时间才能加载

ios - 如何垂直对齐 textView 中的文本?

html - UIWebview - 文本切割

swift - watch 操作系统 2 : Is it possible to get bluetooth signal strength of connectivity between paired iPhone and Apple Watch?