【问题标题】:Listening to Swift Button Disable event监听 Swift 按钮禁用事件
【发布时间】:2016-10-02 19:49:30
【问题描述】:

我想在禁用按钮时将其不透明度设置为 40%。

目前我正在使用我在 StackOverflow 上找到的以下修改代码:

let disabledColor = self.backgroundColor!.colorWithAlphaComponent(0.4)
self.setBackgroundImage(self.imageForColor(disabledColor), forState: .Disabled)

private func imageForColor(color: UIColor) -> UIImage {
    let rect = CGRectMake(0.0, 0.0, 1.0, 1.0)
    UIGraphicsBeginImageContext(rect.size)
    let context = UIGraphicsGetCurrentContext()

    CGContextSetFillColorWithColor(context, color.CGColor)
    CGContextFillRect(context, rect)

    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return image
}

我想我可以在我正在使用的背景颜色上设置不透明度,然后简单地用它创建一个图像并在 .Disabled 状态下使用它,但这没有任何作用。

如果我将 UIColor.redColor() 之类的内容发送到 imageForColor,按钮在禁用时会变为红色...但是不透明度似乎被忽略了。

有人知道这是为什么吗?如果我可以只监听 disabled 事件并触发我自己的函数,或者 Apple 可以让我们为状态而不是背景图像设置背景颜色,那就太好了......

******编辑******

尝试更多的东西,看起来它正确地应用了图像,但它似乎将它应用在背景颜色上,因为它是相同的颜色但具有不透明度,所以很难注意到变化。

我想一个解决方案是只使用背景图像而不是颜色(?),因为我无法替换颜色......

理想情况下,我想对禁用事件的整个按钮应用不透明度。

【问题讨论】:

    标签: ios swift opacity uicolor


    【解决方案1】:

    这不是最好的解决方案,但为了快速,您可以更改按钮的alpha,而不是更改从事件队列中删除点击事件的btn.isUserInteractionEnabled 或btn.isEnabled。

    btn.alpha = 0.5
    

    然后在点击事件中检查sender.alpha是否忽略如下:

    @IBAction func tapOnBtn(_ sender: UIButton) {
        guard sender.alpha == 1 else { return }
        //do your event here
    }
    

    【讨论】:

      【解决方案2】:

      我认为你最好继承UIButton,然后覆盖setEnabled,这样你就可以操纵背景颜色。见this very similar thread。

      【讨论】:

        猜你喜欢
        • 2016-09-03
        • 2023-01-23
        • 1970-01-01
        • 1970-01-01
        • 2017-09-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多