使用imageView外观禁用UIButton而不将isEnabled设置为false

问题描述 投票:0回答:2

我通过设置button.isEnabled = false禁用了一些UIButtons。我发现在禁用按钮时我仍然需要按下按钮。所以,我需要启用按钮但是让它们看起来禁用。这应该可以通过更改按钮的图像/文本的颜色来实现。这些按钮有一个imageView,可以改变isEnabled的颜色并突出显示。如果我停止设置isEnabled,则imageView不再更改。作为一个实验,我将文本添加到button.titleLabel,我可以在按钮上看到imageView和titleLabel。我可以设置button.titleLabel.isEnabled = false并看到titleLabel变为灰色但imageView保持亮起。我没有为imageView找到等效的isEnabled。我尝试过改变imageView颜色的东西,但是UIButton似乎确定只有它才能改变图像颜色,并且只有在设置了button.isEnabled时。有没有办法以编程方式改变图像颜色?

我已经检查了所有建议的问题,但它们都设置为isEnabled。

ios uibutton
2个回答
1
投票

设置按钮的titleColor和titleImage为正常状态,使按钮看起来禁用但不被禁用...

'fakeIsEnabled'没有便捷的方法,所以你必须手动完成


0
投票

似乎问题是在我的xcassetts中我将“渲染为”设置为图像的默认值。如果我强迫它使用“原始图像”,我现在遇到了同样的问题。为什么设置button.isEnabled = false工作是未知的,除非苹果可能太聪明了一半。如果我将其设置为“模板图像”,我可以生效button.imageView.tintColor。通过编程方式加载图像我知道。

所以,步骤是:

  1. 确保图像在xCassetts中设置为模板。
  2. 在IB中设置初始tintColor或以编程方式设置为: button?.imageView?.tintColor = UIColor.white
  3. 然后在代码中根据布尔值更改颜色是: button?.imageView?.tintColor = value ? UIColor.white : UIColor.white.withAlphaComponent(0.5)

我还发现我可以使用tintAdjustmentMode使用代码:

`button?.imageView?.tintAdjustmentMode  = value ? .normal : .dimmed`

它会使图像变暗,可能与button.isEnabled = false一样多。我发现我更喜欢0.5的alpha,因为它更加明显。

© www.soinside.com 2019 - 2024. All rights reserved.