【发布时间】:2013-07-05 15:57:36
【问题描述】:
当我设置按钮的 alpha 时,它也会影响标题的不透明度。有没有办法只针对背景并将标题 alpha 设置为 1.0?
【问题讨论】:
当我设置按钮的 alpha 时,它也会影响标题的不透明度。有没有办法只针对背景并将标题 alpha 设置为 1.0?
【问题讨论】:
这对我有用:
self.myButton.backgroundColor = [UIColor clearColor];
或者如果您不想让它完全清晰,但仍然具有透明度,您可以使用:
self.myButton.backgroundColor = [UIColor colorWithRed:200.0/255.0 green:200.0/255.0 blue:200.0/255.0 alpha:0.5];
第二个示例会为您提供 alpha 0.5 的灰色。
SWIFT 4 更新
myButton.backgroundColor = .clear
或
myButton.backgroundColor = UIColor(red: 200.0/255.0, green: 200.0/255.0, blue: 200.0/255.0, alpha:0.5)
【讨论】:
在 Swift 中:
import UIKit
class SignInUpMenuTableViewControllerBigButton: UIButton {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.applyCustomDesign()
}
func applyCustomDesign() {
// We set the background color of the UIButton.
self.clearHighlighted()
}
override var highlighted: Bool {
didSet {
if highlighted {
self.highlightBtn()
} else {
self.clearHighlighted()
}
}
}
func highlightBtn() {
self.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.0)
}
func clearHighlighted() {
self.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.05)
}
}
斯威夫特 4.2
import UIKit
class SignInUpMenuTableViewControllerBigButton: UIButton {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.applyCustomDesign()
}
func applyCustomDesign() {
// We set the background color of the UIButton.
self.clearHighlighted()
}
override var highlighted: Bool {
didSet {
if highlighted {
self.highlightBtn()
} else {
self.clearHighlighted()
}
}
}
func highlightBtn() {
self.backgroundColor = UIColor.whiteColor().withAlphaComponent(0.0)
}
func clearHighlighted() {
self.backgroundColor = UIColor.whiteColor().withAlphaComponent(0.05)
}
}
【讨论】:
colorWithAlphaCompnent!对于 Swift 3:UIColor.black.withAlphaComponent(0.8)
继承 UIButton 并扩展 setEnabled: 方法似乎可行:
- (void) setEnabled:(BOOL)enabled {
[super setEnabled:enabled];
if (enabled) {
self.imageView.alpha = 1;
} else {
self.imageView.alpha = .25;
}
}
【讨论】:
使用 UIButton,您可以通过将按钮样式设置为自定义而不是圆形矩形来移除背景。这样可以保持标题不变,但删除了按钮背景。如果您在 Storyboards 中执行此操作,则可以在元素属性中更改按钮样式。对于代码,格式为:
UIButton *button = [[UIButton alloc] buttonWithType:UIButtonTypeCustom];
// Setup frame and add to view
【讨论】:
斯威夫特button.backgroundColor = UIColor.white.withAlphaComponent(0.7)
【讨论】:
您只是使用纯色作为背景吗?还是您使用的是图片?
如果您使用的是图像,那么您可以使用内置 alpha 的图像。
如果您使用颜色,则可以在颜色上设置 alpha。
但是,更改任何视图的 alpha 会影响所有子视图。
【讨论】: