xcode 如何使按钮变灰以让用户知道它当前在 iOS 中被禁用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38963628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to grey out a button to let the user know that it is currently disabled in iOS?
提问by Thor
I'm currently developing a simple iOS app using Xcode and Swift. In my app, there is a button that some times is disabled/enabled, depending on something else the user have touched. But when I set "button.enabled = false", I also what the button to grey out, so that the user knows the button is currently disabled. How could this be done?
我目前正在使用 Xcode 和 Swift 开发一个简单的 iOS 应用程序。在我的应用程序中,有一个按钮有时会被禁用/启用,具体取决于用户触摸的其他内容。但是当我设置“button.enabled = false”时,我也将什么按钮变灰,以便用户知道该按钮当前是禁用的。这怎么可能?
回答by slashdot
Use following code for customizing button's title for disabled state. You can call it inside viewDidLoad
:
使用以下代码自定义禁用状态的按钮标题。你可以在里面调用它viewDidLoad
:
button.setTitleColor(UIColor.grayColor(), forState: .Disabled)
If you would like to customize a background colour for disabled button, use approach from this answer: How to change background color of UIButton when it's highlighted
如果您想为禁用按钮自定义背景颜色,请使用此答案中的方法:如何在突出显示时更改 UIButton 的背景颜色
回答by Ishika
You can do this via Storyboard.
Select the button, go to identity inspector and click on state configuration and choose "disable" state.
Then set the background color of the button to gray color.
From here you can customize your UIButton according to your requirements in different states and all you need is to manage setting the state of the button in your code.
您可以通过 Storyboard 执行此操作。选择按钮,转到身份检查器并单击状态配置并选择“禁用”状态。然后将按钮的背景颜色设置为灰色。从这里您可以根据您在不同状态下的要求自定义您的 UIButton,您只需要管理在代码中设置按钮的状态即可。
回答by MikeJ
Swift 3
斯威夫特 3
As accepted answer, but updated for Swift3
作为已接受的答案,但已针对 Swift3 进行了更新
button.setTitleColor(UIColor.gray, for: .disabled)
回答by Duncan C
Standard buttons change their UI when you set the disabled flag to true.
当您将禁用标志设置为 true 时,标准按钮会更改其 UI。
If that doesn't work, you can use slashdot's gray title color change, or do what I often do, which is to set the alpha on the button to .6 or so. (If you have non-uniform contents behind the button, however, this isn't a good choice because whatever's behind the button will show through.)
如果这样不行,你可以用slashdot的灰色标题颜色变化,或者做我经常做的,就是将按钮上的alpha设置为0.6左右。(但是,如果按钮后面有不统一的内容,这不是一个好的选择,因为按钮后面的任何内容都会显示出来。)